java连接MYSQL的问题,各位大牛们看看吧,小弟我疯了、、、
先说一说的,我的系统还有MYSQL的JDBC都已经配置好了、、、
系统变量:
CLSSPATH=D:\progarm two\mysql-connector-java-5.0.5\mysql-connector-java-5.0.5-bin.jar;C:\Program Files\Java\jdk1.6.0_12\bin;
用户变量为:
classpath=.;.;d:\PROGAR~2\JMF\lib\sound.jar;d:\PROGAR~2\JMF\lib\jmf.jar;d:\PROGAR~2\JMF\lib;%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar;.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar;D:\progarm two\mysql-connector-java-5.0.5\mysql-connector-java-5.0.5-bin.jar;
驱动的位置:
D:\progarm two\mysql-connector-java-5.0.5\mysql-connector-java-5.0.5.jar;
配置的ODBC:
Date Source Name :Mysql_Test
Databese:test
代码为:
PHP code
public class Main {
public static void main(String[] args) {
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名字:
String url = "jdbc:mysql://localhost/Mysql_test";
//Mysql配置用户名:
String user = "root";
//Mysql配置密码:
String password = "LJZKID";
try {
//加载驱动程序
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
//连接数据库
Connection con = DriverManager.getConnection(url, user, password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//statement用来执行SQL语言
Statement st = con.createStatement();
//要执行的SQL语言
String sql = "select * from tablename";
//结果集
ResultSet rs = (ResultSet)(Statement) st.executeQuery(sql);
while( rs.next() ) {
//选择col这列数据
String name = rs.getString("col1");
System.out.println("name=" +name );
}
rs.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
------解决方案--------------------
不清楚你现在是报什么错误,你把异常贴出来看看
从你代码import的东西也不太清楚,里面ResultSet rs = (ResultSet)(Statement) st.executeQuery(sql)是完全没有必要强制类型转换
直接ResultSet rs = st.executeQuery(sql)就OK的
你先把异常贴出来,然后import内容也贴出来再讨论吧
------解决方案--------------------
------解决方案--------------------
如以下odbc连接mysql的代码:
1.public static void main(String[] args)
2.{
3.Connection connection = null;
4.Statement statement;
5.ResultSet resultSet;
6.// 加载驱动程序以连接数据库
7.try
8.{
9.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//这个驱动不能是其他的..
10.connection = DriverManager.getConnection("jdbc:odbc:user","root","123"); //user是data Source ,root是用
11.
12.//户名,123是进入mysql的密码
13.System.out.println("open easy");
14.String query = "Select * from userrole";
15.statement = connection.createStatement();
16.resultSet = statement.executeQuery( query );
17.connection.close();
18.System.out.println("close easy");
19.
20.}
21.// 捕获加载驱动程序异常
22.catch ( Class
NotFoundException cnfex )
23.{
24.
System.err.println(
25."装载 JDBC/ODBC 驱动程序失败。" );
26.cnfex.printStackTrace();