简体   繁体   中英

Connecting a Microsoft SQL Server database to my Java project

I am having difficulty linking up my Microsoft SQL Server database table to my java project, having successfully designed my project.

Whenever I run my connection, the project frame successfully loads but the database gets disrupted as I'm notified No suitable driver found for my database.

I have added my sqljdbc4 driver to the library of the project, it's still coming up with such alert.

Here is my connection code:

public void doConnect(){
         try{
         String un = "casey";
        String pw = "****";
        String host = "jdbc:sqlserver://caseydido\\mssqlexpress:1433;databaseName=stock";

        String sql = "SELECT * FROM STAFF_DATA";
        //loading the driver class
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //This is for driver sqljdbc2*
//        Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); /*This is for driver sqljdbc4*/
        Connection conn = DriverManager.getConnection(un, pw, host);
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()){
            System.out.println(rs.getString(1));
            conn.close();
        }

NOTE casey is the username of the database table, the name of the database is STOCK, **** represents my password.

I also tried adding the sqljdbc4 driver path to my system environmental variable path, it still did not work.

First things first:

You need to correct the following code, as mentioned by Mark Rotteveel. Also, consider using meaningful names for your variables so that you understand what goes where.

Connection conn = DriverManager.getConnection(un, pw, host);

To the following:

Connection conn = DriverManager.getConnection(host, un, pw);

You need to add the SQLJDBC connector jar in your project's build path (if you are using an IDE as like ECLIPSE) and also consider adding the path to the connector jar to environmental variable CLASSPATH

Please follow the MSDN Documentation to use the right syntax to construct the host URL. Documentation here .

EDIT-1:

As per your code, the connection is supposed to be closed because of a mistake that you've made. You need to change this from:

while (rs.next()){
    System.out.println(rs.getString(1));
    conn.close();
}

To the following, to solve your problem!

while (rs.next()){
    System.out.println(rs.getString(1));
}
conn.close();

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM