Skip to content

Instantly share code, notes, and snippets.

@malintha
Last active July 19, 2016 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malintha/2b6857bfcee29cc58a9e531e74110f21 to your computer and use it in GitHub Desktop.
Save malintha/2b6857bfcee29cc58a9e531e74110f21 to your computer and use it in GitHub Desktop.
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