package com.jdbc.test;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class Testjdbc {
private static final String url="jdbc:mysql://127.0.0.1:3306/testdata";
private static final String user="root";
private static final String password="root";
public static void main(String[] args) throws Exception {
//1、加载驱动程序
Class.forName("com.mysql.jdbc.Driver") ;
//2、获得数据库的连接
Connection conn=DriverManager.getConnection(url, user, password);
//3、实现增删改查
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select id,name from testtable");
//上面两句提示错误,请高手教我,谢谢
while(rs.next()){
System.out.println(rs.getInt("id")+","+rs.getString("name"));
}
}
}
虽然自己已经找到原因,但还是感谢晴颜的回答
你的包导入错了,import java.beans.Statement;这个包不对
应该是import java.sql.Statement;
public Connection GetConnection() {
// 数据库连接语句
String url = "jdbc:mysql://localhost:3306/database?"
+ "user=root&password=root&useUnicode=true&characterEncoding=UTF8";
// 加载MySql的驱动类
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("[数据库] 找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
}
// 连接数据库
try {
Connection con = (Connection) DriverManager.getConnection(url);
System.out.println("[数据库] 已连接。");
return con;
} catch (SQLException se) {
System.out.println("[数据库] 连接失败!");
se.printStackTrace();
}
return null;
}