访问Java上的数据库数据

时间:2013-05-05 13:45:34

标签: java sql-server jdbc sql-server-2012

我是编程(Java)的新手,我正在尝试使用Microsoft SQL Server 2012来弄清楚如何使用数据库。

我从一本书中获得了以下代码,只更改了本地服务器地址,密码,数据库名称等。

代码无限期运行,只打印“驱动程序已加载!”

此外,我写的密码或用户名似乎没有区别。我尝试过很多不同的地址格式,我从微软和论坛获得。 谁能告诉我这里我做错了什么?谢谢!

package CoisaIdiota;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TesteDB {

    static String ConnectURL = "jdbc:sqlserver://localhost:1433;databaseName=teste";
    static String user = "Adm-PC\\Adm";
    static String pw = "password";
    static Connection conn;

    public static void main(String[] args) {
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    } catch (Exception e) {
        System.err.println("The driver couldn’t be loaded!");
        System.err.println(e);
        e.printStackTrace();
        System.exit(-1);
    }
    System.out.println("The driver has been loaded!");

    try {
        conn = DriverManager.getConnection(ConnectURL, user, pw);
        Statement stmt = conn.createStatement();
        String query = "select ID from nomes";
        ResultSet rs = stmt.executeQuery(query);
        while(rs.next()){
        System.out.println(rs.getString("ID"));
        }
        rs.close();
        stmt.close();
    } catch (SQLException e){
        System.err.println("No connection possible.");
        e.printStackTrace();
        System.err.println("SQLException: " + e.getMessage());
        System.err.println("SQLState: " + e.getSQLState());
        System.err.println("VendorError: " + e.getErrorCode());
        System.exit(-1);
    }


    }
}

2 个答案:

答案 0 :(得分:0)

尝试更改

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

解释here

但可能还没有解决它...我正在寻找:)

这些是我能看到的可能是原因:

  • 服务器未运行
  • 端口错误
  • 驱动程序通过套接字说话,服务器通过端口侦听(尝试连接到127.0.0.1而不是localhost)
  • user / pw不正确

答案 1 :(得分:0)

  

似乎没有区别我写的密码或用户名。

这是因为您在连接之前打印,因此只输出“The driver has been loaded!”:

try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    } catch (Exception e) {
       ....
    }
    System.out.println("The driver has been loaded!");////you print here before the connection

try {
   ....
    }

修复它,在连接后放置你的打印就像那样:

 try {
     conn = DriverManager.getConnection(ConnectURL, user, pw);
     System.out.println("The driver has been loaded!");/////if it printed that's mean you enter the correct username and correct password , if not it will print the exception 
     ....
}