java如何用mysql

更新时间:02-10 教程 由 鬓上 分享

Java是一种广泛使用的计算机编程语言,而MySQL是最受欢迎的开源数据库。Java如何使用MySQL是一个常见的问题,下面我们将介绍一些基本的步骤。

第一步是获取适当的MySQL驱动程序。在Java中使用JDBC(Java数据库连接)连接MySQL数据库需要下载并使用适当的JDBC驱动程序。可以从MySQL官方网站(www.mysql.com)下载MySQL Connector / J JDBC驱动程序。

import java.sql.*;public class MysqlConn {public static void main(String[] args) {try {Class.forName("com.mysql.jdbc.Driver");Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");System.out.println("Connected to MySQL");} catch (Exception e) {System.out.println("Not connected to MySQL");e.printStackTrace();}}}

在上面的代码中,我们首先使用Class.forName方法加载MySQL驱动程序。然后,我们使用DriverManager.getConnection方法连接到我们的MySQL数据库并提供用户名和密码。

第二步是创建一个语句对象。使用Java语言向MySQL数据库发送请求需要首先创建一个Statement对象。通过使用Connection.createStatement()方法,将Statement对象与连接关联起来。然后,使用Statement.executeUpdate()方法执行SQL语句,该方法返回更新的行数。

import java.sql.*;public class MysqlConn {public static void main(String[] args) {try {Class.forName("com.mysql.jdbc.Driver");Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");Statement stmt = c.createStatement();String sql = "INSERT INTO persons (LastName, FirstName, Address) VALUES ('Doe', 'John', '123 Main St')";stmt.executeUpdate(sql);System.out.println("Record inserted into MySQL");} catch (Exception e) {System.out.println("Record not inserted into MySQL");e.printStackTrace();}}}

在上面的代码中,我们创建了一个Statement对象,然后使用executeUpdate方法执行INSERT SQL语句。

第三步是开始查询数据。执行SELECT语句并使用ResultSet对象处理结果。通过Statement.executeQuery()方法执行查询语句,而不是使用executeUpdate()方法。查询结果将作为ResultSet对象返回。

import java.sql.*;public class MysqlConn {public static void main(String[] args) {try {Class.forName("com.mysql.jdbc.Driver");Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");Statement stmt = c.createStatement();String sql = "SELECT * FROM persons";ResultSet rs = stmt.executeQuery(sql);while(rs.next()){System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));}} catch (Exception e) {e.printStackTrace();}}}

在上面的代码中,我们执行了SELECT语句并使用ResultSet对象打印结果。

总结,Java可以使用MySQL进行各种操作,如插入、更新、删除和查询记录。通过在Java中使用适当的JDBC驱动程序和语句对象,可以与MySQL数据库进行连接和通信。

声明:关于《java如何用mysql》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2261859.html