package javaapplication1;
import java.sql.*;
public class JavaApplication1{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/TEST/ANKUR1";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection("TEST1/ANKUR","root","school");
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
System.out.println(e);
}
}
}我已经在我的机器上安装了MySQL 5.5,并将Java-connector.jar文件复制到所需的文件夹中。我的数据库是test1,表是ankur。请看,我使用这段代码只是为了检查与我的NetBeans 7的连接。有什么建议吗?
发布于 2011-06-29 18:25:41
您在getConnection(...)中实际使用的URL是错误的。您不应该只输入要使用的表的名称。您需要有一个完整的URL,以便JDBC系统知道它应该使用mysql驱动程序以及mysql驱动程序需要连接到哪里。
重新检查你复制的示例,看看他们在哪里使用了"url“变量。
发布于 2011-06-29 18:32:27
使用MySQL连接器/J驱动程序时的JDBC URL format为:
jdbc:mysql://host:port/database=propertyValue1=propertyValue2...
因此,在您的案例中使用的实际URL应该是(如果数据库安装在本地计算机上,名称为TEST,并侦听默认的MySQL端口3306):
测试jdbc:mysql://本地主机:3306/
而不是下面的。
测试/分析1
请记住,DriverManager类使用JDBC URL来确定应该使用哪个驱动程序连接到数据库以及数据库所在的位置。不连接到JDBC中的表;相反,连接到数据库(或模式),然后对表发出SELECT查询。因此,您的方法将如下所示:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/TEST","root","school");
System.out.println("Connected to the database");
PreparedStatement pStmt = conn.prepareStatement("SELECT * FROM ANKUR");
ResultSet rs = pStmt.executeQuery();
...
//Process the contents of the ResultSet
...
rs.close();
pStmt.close();
conn.close();应该注意,在finally块中关闭ResultSet、PreparedStatement和Connection对象是一种很好的做法。
https://stackoverflow.com/questions/6518957
复制相似问题