一、安装driver
下载JDBC驱动mysql-connector-java-5.0.5.zip。然后将其解压缩到任一目录。假设解压到D盘,然后将其目录下的mysql-connector-java-5.0.5-bin.jar加到classpath里,具体如下:“我的电脑”-> “属性” -> “高级” -> “环境变量”,在系统变量那里编辑classpath,将D:mysql-connector-java-5.0.5mysql-connector-java-5.0.5-bin.jar加到最后,在加这个字符串前要加“;”,以与前一个classpath区分开。然后确定。
二、链接mysql
新建project命名MysqlTest
(1)执行以下代码
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while(rs.next()){
System.out.println(rs.getString("deptno"));
}
}catch(ClassNotFoundException ex){
ex.printStackTrace();
}catch(SQLException ex){
System.out.println("SQLException: "+ ex.getMessage());
}finally{
try{
if(rs != null){
rs.close();
rs = null;
}
if(stmt != null){
stmt.close();
stmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
如果出现ClassNotFound 错误,则手动引入包: 在MysqlTest根目录右击->BuildPath->Add External Archives->找到步骤一种的D:mysql-connector-java-5.0.5mysql-connector-java-5.0.5-bin.jar, 应如后重新运行即可。