1. Load the SQL Servser 2005 Driver (Sqljdbc.jar) and register the driver with the DriverManager
Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
2. Get the connection
conn = drivermanager.getconnection (URL, user, password);
Url= "jdbc:sqlserver://localhost:1433; Databasename= database Name "
3. Processing the written SQL with preprocessing objects
4. Passing parameters to SQL with preprocessing objects (optional)
5. Execute SQL (query with executequery (); Add, delete, update with executeupdate ())
Connection conn = null;
String url = "jdbc:sqlserver://localhost:1433; Databasename=test ";
String user = "sa";
String password = "";
String sql = "SELECT * from users";
try {
Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = drivermanager.getconnection (URL, user, password);
PreparedStatement pstm = conn.preparestatement (sql);
ResultSet rs = Pstm.executequery ();
while (Rs.next ()) {
System.out.println (rs.getstring ("account"));
}
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
If SQL Servser is installed, the runtime will error, Com.microsoft.sqlserver.jdbc.SQLServerException: TCP/IP connection to the host failed.
WORKAROUND: Find SQL servser 2005-config tool-sql servser configuration manager-Network Configuration-mssqlserver Protocol-tcp/ip-Right-click Set to enable-restart service in all programs to resolve
SQL Server 2005 JDBC Connection