当前位置 : 主页 > 编程语言 > java >

JDBC连接MySQL

来源:互联网 收集:自由互联 发布时间:2021-06-28
JDBC import java.sql*;public class TestJDBC { public static void main(String[] args) { Connection conn=null; Statement stmt=null; ResultSet rs=null; String sql="select * from student"; try { //1.加载驱动 Class.forName("com.mysql.jdbc.Dr
JDBC
import java.sql*;

public class TestJDBC {
    public static void main(String[] args) {

        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        String sql="select * from student";

        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.连接mysql数据库
            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","1234567");
            //3.通过数据库的连接操作数据库,实现增删改查
            stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()) {
                System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getInt("age"));
            }
        }catch(ClassNotFoundException e) {
            e.printStackTrace();
        }catch(SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs!=null) {
                    rs.close();
                }
                if(stmt!=null) {
                    stmt.close();
                }
                if(conn!=null) {
                    conn.close();
                }
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
网友评论