Java连接数据库

1、注册驱动

String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);

2、连接数据库

String url = "jdbc:mysql://localhost:3306/dbname";
String user = "root";
String password = "123";
Connection conn = DriverManager(url, user, password);

3、定义sql

String sql = "select * from student";

4、定义执行sql的Statement对象

Statement stem = conn.createStatement();

5、执行查询SQL,执行DDL或者DML操作时使用executeUpdate方法

ResetSet rs = stemt.executeQuery(sql);

6、处理查询结果

while(re.next()){
    System.out.println(rs.getString("字段名称"));      
}

7、关闭statemt, conn

if(stemt != null){stemt.clost();}
if(conn != null){conn.close();}

  

posted @ 2020-09-23 17:35  人生只若初相见  阅读(145)  评论(0编辑  收藏  举报