I'm trying to create a simple Java application to connect to a Microsoft SQL Server database for a login interface.
I’ve installed the following:
JDK 24
MySQL Connector/J 9.2.0
Here's the code I'm using:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.sql.SQLException;public class ConnectToSQLServer { public static void main(String[] args) { // Database URL String url = "jdbc:sqlserver://localhost:1433;databaseName=YourDatabaseName"; // Database credentials String user = "yourUsername"; String password = "yourPassword"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Load the JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Step 2: Establish the connection conn = DriverManager.getConnection(url, user, password); // Step 3: Create a statement object stmt = conn.createStatement(); // Step 4: Execute a query String sql = "SELECT id, name FROM yourTable"; rs = stmt.executeQuery(sql); // Step 5: Process the result set while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id +", Name: " + name); } } catch (ClassNotFoundException e) { System.err.println("JDBC Driver not found."); e.printStackTrace(); } catch (SQLException e) { System.err.println("SQL Exception occurred."); e.printStackTrace(); } finally { // Step 6: Close the result set, statement, and connection try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.err.println("Error closing resources."); e.printStackTrace(); } } }}
However, when I try to compile this code, I get the following error:
java: illegal character: '\ufeff'
What I’ve Tried:
I verified the syntax and everything seems fine.
I retyped the first few lines manually.
I made sure my IDE (IntelliJ IDEA) is using UTF-8 encoding.
Goal:
I want to create a simple login interface that connects to Microsoft SQL Server and retrieves user data.
Any help would be appreciated!
I wrote a simple Java application that connects to a Microsoft SQL Server database using JDBC. I expected the code to compile and run successfully, then retrieve and print data from a table named yourTable
. The logic and syntax looked correct to me, and I followed standard steps: loading the driver, creating a connection, executing a query, and processing the result set.
Despite these attempts, the error persisted. I’m looking for help identifying why this character is causing the issue and how to remove it properly so the program can compile and connect to SQL Server as expected.