-
-
Save malintha/2b6857bfcee29cc58a9e531e74110f21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.*; | |
public class Main { | |
public static void main(String[] args) { | |
// Create a variable for the connection string. | |
String connectionUrl = "jdbc:sqlserver://localhost;" + | |
"databaseName=ms_test;user=username;password=password"; | |
// Declare the JDBC objects. | |
Connection con = null; | |
ResultSet rs = null; | |
try { | |
// Establish the connection. | |
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); | |
con = DriverManager.getConnection(connectionUrl); | |
// Create and execute an SQL statement that returns some data. | |
PreparedStatement ps = con.prepareStatement("INSERT INTO employees VALUES (?,?)"); | |
ps.setString(1, "Sunil"); | |
ps.setString(2, "23"); | |
ps.executeUpdate(); | |
ps.setString(1, "Saman"); | |
ps.setString(2, "23"); | |
ps.executeUpdate(); | |
PreparedStatement ps_1 = con.prepareStatement("SELECT * FROM employees"); | |
rs = ps_1.executeQuery(); | |
// Iterate through the data in the result set and display it. | |
while (rs.next()) { | |
System.out.println("Name : "+rs.getString(1) + " | Age : "+rs.getString(2)); | |
} | |
} | |
// Handle any errors that may have occurred. | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
finally { | |
if (rs != null) try { rs.close(); } catch(Exception e) {} | |
if (con != null) try { con.close(); } catch(Exception e) {} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment