The steps are divided into 3 parts: 1. Configuring 1433 ports through SQL Server Configuration Manager
2. Add the Sqljdbc41.jar class library to the corresponding project
3. Connecting to a database in a Java program
Step 1: Open SQL Server Configuration Manager, click the TCP/IP right button and select Enable. The disabled TCP/IP protocol is turned on.
The SQL Server (MSSQLSERVER) service is then restarted, allowing the TCP/IP protocol to take effect.
Step 2: Download the Sqljdbc41.jar class library to the Microsoft website. http://www.microsoft.com/zh-CN/download/details.aspx?id=11774
Unzip the downloaded package and find the Sqljdbc41.jar class library.
Then go to the Eclipse interface, find the current project file, right-click, select Properties->libraries->add External jars-> find the Sqljdbc41.jar class library we just downloaded to add.
Step 3:
Import java.sql.*;
public class Test2 {
public static void Main (string[] args) {
TODO auto-generated Method Stub
PreparedStatement Ps=null; (statement can also be used here, depending on the situation)
Connection Ct=null;
ResultSet Rs=null;
try {
1. Load Driver
Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url= "Jdbc:sqlserver://localhost:1433;databasename=test1";
String user= "sa";//sa Super Admin
String password= "123456";//Password
2. Connect
Ct=drivermanager.getconnection (Url,user,password);
3. Create the Send side
pstmt = Conn.preparestatement ("INSERT into the staff (name, age) VALUES (?,?)");
Set the specific value of the insert by using the Set method in the PreparedStatement object
Pstmt.setstring (1, Newen);
Pstmt.setint (2, +);
Pstmt.executeupdate ();
//Insert Success Prompt
System.out.println ("Insert a data record successfully!" ");
}
} catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}finally{
Close resources to enhance program robustness
try {
if (rs!=null) {
Rs.close ();
}
if (ps!=null) {
Ps.close ();
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
At this point, the JDBC Connection database over!!!
The effect is similar to the following:
Eclipse uses JDBC to connect to the latest and most detailed tutorials in the history of SQL Server 2012 databases (April 2015 pro-Test)