菜鸟教程的代码,一模一样。。。。链接
最后连接成功,输出了结果= =也不枉费我把代码一个一个敲出来了
主要就是导入包的时候需要注意一下:
1.右键点击项目选择属性
2.我的汉化过了。选择java构建路径,选择库,类路径然后添加外部jar
3.确定之后就可以愉快的写代码了
用的是菜鸟教程提供的包,和我的5.5版本mysql不冲突就好
package com.runoob.test;
import java.sql.*;
public class MysqlDemo {
//JDBC驱动名与数据库url
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/runoob";
//数据库与密码
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//打开链接
System.out.println("链接数据库中。。。");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//执行查询
System.out.println("实例化Statement对象。。。。");
stmt = conn.createStatement();
String sql;
sql = "select id,name,url from websites";
ResultSet rs = stmt.executeQuery(sql);
//展开结果集数据库
while(rs.next()) {
//通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
//输出数据
System.out.print("ID: "+id);
System.out.print(", name: "+name);
System.out.print(", url: "+url);
System.out.println();
}
//完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException es) {
//处理JDBC错误
es.printStackTrace();
}catch(Exception e) {
//处理Class.forName错误
e.printStackTrace();
}finally{
//关闭资源
try {
if(stmt!=null) {
stmt.close();
}
}catch(SQLException es) {
es.printStackTrace();
}
}
System.out.println("GOOD BYE!");
}
}
下面是运行结果