Wednesday, February 26, 2014

Hoe to Create/Establish a Java--SQL Server Database Connection

Ooo!k! First things first; you have to configure SQL Server, i mean, create an instance (sql server authentication ~>"optional"), Grant permissions, Enable TCP/IP, Get port number then Restart SQL service.
After that, you have to get/download ms sql server jdbc driver. if you already have then, unzip to any dir/location of your choice. all you need is the sqljdbc4.jar OR sqljdbc.jar file. Copy either file, based on you Connection/DBase type, paste on your desktop for easy access.
Next;
Add the sqljdbc.jar file in your 'compile time library'... see example on adding sqljdbc.jar using NetBeans IDE.

From your file menu item, click on "project properties (project_name); 
under categories list, select libraries

Next, click on 'Add JAR/Folder' button the add the sqljdbc.jar file, then click 'Ok'....Up next is your code.

Your code should look similar to the below code:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBase {

     public static void main(String [] args) throws SQLException, ClassNotFoundException
     {
        try
        {
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    String ConnString =  "jdbc:sqlserver://localhost:1433; databaseName= clems; username=Douby;password=clems";

        Connection conn = (DriverManager.getConnection(ConnString));
        Statement stmt = conn.createStatement();
        String sql_stmt = "Select First_Name from Employee";
       ResultSet rs = stmt.executeQuery(sql_stmt);

        while (rs.next())
        {
            String a = rs.getString("First_Name");
            System.out.println(a);
        } 
        }        
        catch (SQLException | ClassNotFoundException sql_cnfe)
        {
            System.out.println(" ClassNotFoundException thrown");
            sql_cnfe.printStackTrace();
        }
    }
  }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Still don't get it? feel free to reach me
   

  


No comments: