JDBC MySQL
JavaJDBC连接MySQL的基本流程。
import java.sql.*;
public class demo01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.用户信息和url
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
String username="root";
String password="123456";
//3.连接成功,获得数据库对象 Connection 代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4.获得执行SQL的对象,Statement
Statement statement = connection.createStatement();
//5.用Statement去执行SQL,可能存在结果,查看返回结果
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("name=" + resultSet.getObject("name"));
System.out.println("gender=" + resultSet.getObject("gender"));
System.out.println("email=" + resultSet.getObject("email"));
System.out.println("address=" + resultSet.getObject("address"));
System.out.println("---------------------------");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}