First we download the Microsoft JDBC Driver package
https://www.microsoft.com/en-us/download/details.aspx?id=11774
Download well after we open as
Click Unzip extract out, and find sqljdbc42 This file, take this file to configure environment variables, configuration I will not say, configured as well as
After the configuration is complete, we open our SQL Server Configuration Manager to configure our connection port
Locate the SQL Server network Configuration->mssqlserver protocol, if TCP/IP is turned off, turn it on, double-click the TCP/IP protocol, Select the IP Address tab to change the IP address of the IP1 and IP10 to 127.0.0.1, the port is changed to 1433, whether the activity is changed to IS, the other default, then the Ipaii TCP port to 1433, modified after the completion of the Telnetor Netstat-an command to see if Port open does not open as
Connection is successful, then configure the login user in SQL Server, you can add one yourself, I use the default SA
Log in to the database, the operation is as follows: Security, login name, right-click the sa select attribute, set the password yourself, in the right click on the server select the properties of the following circle hit
All of the above are configured so that we can then write the code, open our Eclipse and import the jar into it.
Create a new project, create a new Lib folder, and copy the Sqljdbc42 in, as
In right-click it select Build Path at point first, import later on code
Packagetest;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet; Public classDemo { Public Static voidMain (string[] args) {String user= "SA"; String Password= "Admin"; Connection Conn; Statement stmt; ResultSet rs; String URL= "jdbc:sqlserver://127.0.0.1:1433;databasename=student_db;"; String SQL= "SELECT * FROM Student"; Try { //connecting to a databaseconn =drivermanager.getconnection (URL, user, password); //Creating statement Objectsstmt =conn.createstatement (); //Executing database query statementsrs =stmt.executequery (SQL); while(Rs.next ()) {String ID= Rs.getstring ("s_id"); String name= Rs.getstring ("S_name"); floatScore = rs.getfloat ("S_score"); String Sex= Rs.getstring ("S_sex"); System.out.println ("School Number" +id+ "name" +name+ "score" +score+ "gender" +sex); } if(rs! =NULL) {rs.close (); RS=NULL; } if(stmt! =NULL) {stmt.close (); stmt=NULL; } if(Conn! =NULL) {conn.close (); Conn=NULL; } } Catch(SQLException e) {e.printstacktrace (); System.out.println ("Database connection Failed"); } }}
Java connection SQL Server data simple operation