日期:2014-05-20  浏览次数:20728 次

java链接数据库问题
package com.yzw;

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

public class test_1 {

public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement stmt = conn.createStatement();
/*stmt.executeUpdate("insert into t_user values(null,'wenqi','888888')");*/
ResultSet rs = stmt.executeQuery("select * from t_user");
 
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
rs.next();
rs.close();
stmt.close();
conn.close();
}

}


运行报异常,不知道为什么。求解。JDBC感觉就是学不好,只有去硬记。

------解决方案--------------------
Java code

package com.yzw;

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

public class test_1 {

public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement stmt = conn.createStatement();
/*stmt.executeUpdate("insert into t_user values(null,'wenqi','888888')");*/
ResultSet rs = stmt.executeQuery("select * from t_user");
  try {
            while (rs.next()) {
                System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

rs.close();
stmt.close();
conn.close();
}