记笔记,直接贴代码!
import java.sql.*; public class mysql_connect { // 连接数据库文件 // throws ClassNotFoundException 用于抛出一场,否则编译器报错 SQLException抛出sql异常 public static void main(String[] args) throws ClassNotFoundException, SQLException { // 加载驱动 // 注意:新版本已启用,不需要加载驱动即可连接 //Class.forName("com.mysql.jdbc.Driver"); String mysql_url = "jdbc:mysql://localhost:3306/my_db_one"; String mysql_name = "user"; String mysql_password = "123456"; /** * DriverManager为驱动管家 * getConnection为驱动管家下的一个连接方法,@perams {url, name, password} * */ // 创建连接对象 Connection connection = DriverManager.getConnection(mysql_url, mysql_name, mysql_password); // 判断sql对象是否为空,为空即为连接失败 if (connection == null) { System.out.println("连接失败"); return; } else { System.out.println("连接成功"); } Statement statement = connection.createStatement(); String select_sql = "select * from person"; // 数据对象 ResultSet resultset = statement.executeQuery(select_sql); while (resultset.next()) { System.out.println(resultset.getInt("id")); } resultset.close(); statement.close(); connection.close(); } }