用java连接mysql问题

sinopatic 2006-05-29 06:00:27
代码如下:
package ch13;

import java.sql.*;
public class UseDriverManager {
public static void main(String args[]){
String url="jdbc:mysql://localhost/sql_test";
String userName="root";
String password="sinopatic";
Connection conn=null;

try{
System.out.println("Before the first time connect to Database");
conn=DriverManager.getConnection(url,userName,password);
System.out.println("After the first time connect to Database");
}
catch(SQLException e){
System.out.println("There are some problems occur when first connect to database");
}
if(conn==null)
System.out.println("First connection fail...");
else
System.out.println("First connection successful!");

try{
System.out.println("\n Before mount the driver");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("After mount the driver");
}
catch(ClassNotFoundException e){
System.out.println("There are some problems occur when mount the driver...");
}

try{
conn = null;
System.out.println("\n Before the sencond time connecting the the Database");
conn=DriverManager.getConnection(url,userName,password);
System.out.println("After the second time connect to the Database");
}
catch(SQLException e){
System.out.println("There are some problems occur when first connect to database");

}
if(conn==null)
System.out.println("Sencond connection fail...");
else
System.out.println("Second connection successful!");

try{
conn.close();
}
catch(SQLException e){
System.out.println("There are some problems occur when close the connection to the Database");
}




}
}

------------------------
启动mysql,在eclipse中运行,连接不上:
ClassNotFoundException
Insert SQLException
Exception in thread "main" java.lang.NullPointerException
at ch13.UseDriver.main(UseDriver.java:33)
...全文
164 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
sinopatic 2006-05-31
  • 打赏
  • 举报
回复
搞定了~谢谢大家了啊
believefym 2006-05-31
  • 打赏
  • 举报
回复
用了eclipse就别设什么环境变量了,eclipse自己有个包管理的,把包添加到user library,然后在工程里导入就可以了
sinopatic 2006-05-31
  • 打赏
  • 举报
回复
还要设置环境变量的啊..
sinopatic 2006-05-31
  • 打赏
  • 举报
回复
我试试看....
meadking 2006-05-29
  • 打赏
  • 举报
回复
1这是jdbc的驱动!下载mysql-connector-java-3.1.10-bin.jar
2设置jdbc的classpath
SET CLASSPATH=.;%JAVA_HOME%\mysql-connector-java-3.1.10-bin.jar
3程序中加载驱动Class.forName
4个人建议:先测试加载的驱动是否成功!然后再接着下一步!呵呵一步一步来了!呵呵!
http://my.6cncn.cn
6cncn.cn
6cncncn@gmail.com
blueswind8306 2006-05-29
  • 打赏
  • 举报
回复
1.mysql的默认连接端口是3306,而你的连接字符串没有加上端口号.
将String url="jdbc:mysql://localhost/sql_test";
改为String url="jdbc:mysql://localhost:3306/sql_test";
试试
2.看看你有没有引mysql的jar包!
gyang 2006-05-29
  • 打赏
  • 举报
回复
太乱了,写的啥奥。
believefym 2006-05-29
  • 打赏
  • 举报
回复
Class.forName("com.mysql.jdbc.Driver");
----
放前面去
try catch太多了,直接在main上throw掉,然后去掉try catch便于测试
KOfeng 2006-05-29
  • 打赏
  • 举报
回复
必须先加载驱动Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");,从而才能交由驱动管理器控制.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧