package com.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class mySqlJdbc {
public static void main(String[] args) {
ResultSet rs=null;
Statement st=null;
Connection cn=null;
try {
//加载mysql驱动
Class.forName("com.mysql.jdbc.Driver");
//获得连接
String url = "jdbc:mysql://localhost:3306/employee";
String user = "root";
String password = "admin";
cn = DriverManager.getConnection(url, user, password);
//准备执行语句
st = cn.createStatement();
String sql="select * from employee";
//执行sql语句返回给resultset结果集
rs = st.executeQuery(sql);
//读取resultset结果集中的数据
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//各种关闭,注释:后用先关
}finally{
try {
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(cn!=null){
cn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
切记:jar要导入eclipse中,下面提供mysqljar下载地址:
http://dev.mysql.com/downloads/connector/j/