MySQL是一个常用的关系型数据库管理系统,其中使用Java语言进行开发的应用程序也需要使用MySQL数据库。在Java程序中连接MySQL数据库需要使用相应的MySQL JDBC驱动程序包,该驱动程序包可以使Java应用程序与MySQL数据库进行交互。
在Java中使用MySQL JDBC驱动程序包需要定义一个数据库连接对象,使用指定的URL、用户名和密码连接到数据库;还需要使用SQL查询语句来查询、插入、更新和删除数据,然后使用ResultSet对象来访问和处理查询结果。
MySQL提供多种开发语言的API,其中使用Java语言进行开发的API称为MySQL Connector/J。MySQL Connector/J是一个纯Java语言的JDBC驱动程序包,旨在与MySQL数据库进行通信。为了使用MySQL Connector/J,需要在Java程序中引入相应的驱动程序包。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mysql.jdbc.Driver; public class MySQLConnection { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //注册MySQL驱动程序 Class.forName("com.mysql.jdbc.Driver"); //连接数据库 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false", "root", "123456"); //执行查询 stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM student_info"); //遍历查询结果 while (rs.next()) { System.out.println(rs.getString("id") + "\t" + rs.getString("name") + "\t" + rs.getString("age")); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { //释放资源 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
上述代码使用了MySQL Connector/J中的Driver类来注册MySQL驱动程序,使用getConnection方法连接到MySQL数据库,并使用createStatement方法执行查询语句。其中,JDBC URL告诉驱动程序连接到哪个数据库(在这里是student),连接字符串中需要指定数据库的主机名、端口号、数据库名和用户名/密码。
上一篇 mysql的驱动程序叫什么
下一篇 css text清格式