Skip to content

Instantly share code, notes, and snippets.

@Malintha

Malintha/Main.java Secret

Last active Jul 19, 2016
Embed
What would you like to do?
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
You can’t perform that action at this time.