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();}