1、要在项目中导入数据库驱动jar 包:
2、完整代码:
import java.sql.*;
public class TestJDBC1 {
/**
* @param args
*/
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
String url = "jdbc:mysql://127.0.0.1:3306";
con = DriverManager.getConnection(url,"root","123");
//创建语句对象
st = con.createStatement();
//执行查询语句
String sql = "SELECT OP_CODE,OP_NAME FROM safety.t_op";
rs = st.executeQuery(sql);
//遍历结果集
while(rs.next()){
System.out.println(rs.getString("OP_CODE"));
System.out.println(rs.getString("OP_NAME"));
// System.out.println(rs.getString(“tie”));
// System.out.println(rs.getString(“stelephone”));
// System.out.println(rs.getString(“borrowcount”));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//释放资源
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}