JDBC
1.使用DriverManager 进行加载驱动 Driver
2.通过驱动的加载拿到连接对象 Connection
3.通过connection对象获取到 Statement
4.使用Statement对象 进行sql查询或更新
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args)throws ClassNotFoundException,SQLException{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//拿到连接对象
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//获取到statement
Statement st=conn.createStatement();
//进行查询,返回结果集
ResultSet rs= st.executeQuery("select * from tb1");
//对结果进行遍历
while(rs.next()) {
System.out.println(rs.getString("uername")+":"+rs.getInt("age")+":"+rs.getFloat("salary"));
}
rs.close();
st.close();
conn.close();
}
}
工具类
package com.openlab.web;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
private String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/demo";
private static String username="root";
private static String password="123456";
private Connection conn=null;
private Statement st=null;
private ResultSet rs=null;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123456");
}
public static void jdbcClose(Connection conn,Statement st,ResultSet rs){
try {
rs.close();
if(rs!=null){
rs=null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
st.close();
if(st!=null){
st=null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
conn.close();
if(conn!=null){
conn=null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
测试类:
package com.openlab.web;
import java.sql.Connection;
import com.oplb.web.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtilsTest {
public static void main(String[] args) {
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try {
conn=JDBCUtils.getConnection();
st=conn.createStatement();
rs=st.executeQuery("select * from tb1");
while(rs.next()){
System.out.println(rs.getString(1)+":"+rs.getInt(2)+":"+rs.getFloat(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtils.jdbcClose(conn, st, rs);
}
}
}