To connect MS SQL database using jdbc driver in java, we need to download jdbc driver for MS SQL server. Refer below link to download MS SQL jdbc driver file.
Add external Jar file to project:
- Right click on project,
- Go to properties → Java Build Path → Click on Library tab
- Add external library and click on apply and close button.
Create connection:
1 2 3 4 5 6 7 |
String UserName="usrName"; String Password="pwd"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String DB_URL ="jdbc:sqlserver://<hostname>\\<instance_name>;databaseName=sample"; //OR by using ip DB_URL ="jdbc:sqlserver://192.168.0.10:3324\\<instance_name>;databaseName=sample"; Connection con = DriverManager.getConnection(DB_URL, UserName, Password); |
Execute prepared statement for Insert query
1 2 3 4 5 6 7 |
String insertQuery = "INSERT INTO EMP (EmpID,EmpAge,EmpSal) VALUES (?,?,?) "; PreparedStatement preparedStmt = con.prepareStatement(insertQuery); preparedStmt.setInt(1, 50); preparedStmt.setInt(2, 40); preparedStmt.setInt(3, 14000); preparedStmt.executeUpdate(insertQuery); preparedStmt.close(); |
Execute select query and print data
1 2 3 4 5 6 7 8 9 10 11 |
//Use connection from above mentioned code String selectQuery = "Select EmpID, EmpAge,EmpSal from EMP where EmpID=1"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectQuery); while (rs.next()) { System.out.println("ID: "+rs.getInt("EmpID")); System.out.println("Age: "+rs.getInt("EmpAge")); System.out.println("Sal: "+rs.getInt("EmpSal")); } stmt.close(); con.close(); |