1.idea+MySQL主要有以下七步:
加载驱动、创建连接、写sql、得到statement对象、执行sql、处理结果集、关闭资源。
2.以上操作的简单测试源码如下(当然要先在MySQL建表,然后连接数据库):
package com.zhongruan;
import java.sql.*;
public class Test {
public static void main(String[] args) {
ResultSet resultSet=null;
PreparedStatement statement=null;
Connection connection=null;
try {
//1加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2创建连接
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/idea?useSSL=true&characterEncoding=utf-8&user=root&password=root");
//3.写sql
String sql="select * from userinfo";
//4.得到statement对象
statement = connection.prepareStatement(sql);
//5.执行sql
resultSet = statement.executeQuery();
//6处理结果集
while (resultSet.next()){
System.out.print(" id: "+resultSet.getInt(1));
System.out.print(" username: "+resultSet.getString(2));
System.out.print(" password: "+resultSet.getString(3));
System.out.println("-----------");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//7关闭资源
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){