Connecting to SqlServer

Getting the JDBC Driver

  1. In order to connect to SqlServer with Java, you first must have the JDBC Driver. You can download it here.

  2. After downloading. run the .exe file to generate a folder with your JDBC Driver in it.

  3. Next go to your Java project. Right click on the project name and go to BuildPath >> Configure Build Path.

  4. 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

  1. Start by adding "java.sql.*" to your import statements.

  2. 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]);

  3. You should now have your open connection to SqlServer


Reading from the Database

  1. Start by creating a Statement object and setting it to connection.createStatement().

    i.e: Statement s1 = conn.createStatement();

  2. 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]");

  3. 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()){

                }
          }

  4. 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

  1. Start by creating a Statement object and setting it to connection.createStatement().

    i.e: Statement s1 = conn.createStatement();

  2. 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

  1. Start by creating a Statement object and setting it to connection.createStatement().

    i.e: Statement s1 = conn.createStatement();

  2. 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 +"'");