Connecting to SqlServer
Getting the JDBC Driver
-
In order to connect to SqlServer with Java, you first must have the JDBC Driver. You can download it here.
-
After downloading. run the .exe file to generate a folder with your JDBC Driver in it.
-
Next go to your Java project. Right click on the project name and go to BuildPath >> Configure Build Path.
-
Click "Add External Jars" and navigate to your newly downloaded JDBC Driver. Select the one called "sqljdbc4.jar". Click "Open".
Setting up the SQL Connection
-
Start by adding "java.sql.*" to your import statements.
-
Create a new Connection object. After that do a Class.forName() to obtain your driver.
Initialize your connection by setting it to DriverManager.getConnection() and providing your Connection String, UserName, and Password. Substitute your own parameters within the brackets.
i.e: Connection conn;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection([ConnectionString], [UserName], [Password]);
-
You should now have your open connection to SqlServer
Reading from the Database
-
Start by creating a Statement object and setting it to connection.createStatement().
i.e: Statement s1 = conn.createStatement();
-
Next create a ResultSet and set it to your read statement. Substitute your own parameters within the brackets.
i.e: ResultSet rs = s1.executeQuery("SELECT * FROM [Table Name]");
-
Check to see if your ResultSet is not equal to null. Inside that if statement create a while loop that runs off ResultSet.next()
i.e: if(rs!=null){
while (rs.next()){
}
}
-
Inside the while loop. Read the data using the get statement that matches the type of data you are reading. Substitute your own parameters within the brackets.
i.e: NameResult[i] = rs.getString("[Column Name]");
idResult[i] = rs.getInt("[Column Name]");
Adding to the Database
-
Start by creating a Statement object and setting it to connection.createStatement().
i.e: Statement s1 = conn.createStatement();
-
Next call your Statements executeUpdate command and pass it your Add statement. Substitute your own parameters within the brackets.
i.e: s1.executeUpdate("INSERT INTO [Table Name] ([Column Name]) values ('"+ value +"')");
Deleting from the Database
-
Start by creating a Statement object and setting it to connection.createStatement().
i.e: Statement s1 = conn.createStatement();
-
Next call your Statements executeUpdate command and pass it your Add statement. Substitute your own parameters within the brackets.
i.e: s1.executeUpdate("DELETE FROM [Table Name] WHERE [Column Name]='"+ value +"'");