Java如何将记录插入数据库表?
在此示例中,您将学习如何创建一个程序以将数据插入数据库表中。要插入数据,我们需要连接到数据库。获得连接后,您可以从中创建一个java.sql.Statement对象,并使用该对象可以执行一些查询字符串。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class InsertStatementExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { //创建一个语句对象。 Statement stmt = connection.createStatement(); String sql = "INSERT INTO books (isbn, title, published_year) " + "VALUES ('9781617291999', 'Java 8 in Action', 2015)"; //在语句对象中调用execute方法 //并传递查询。 stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } }
以下是创建books表的脚本。
CREATE TABLE `books` ( `isbn` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `published_year` int(11) DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`isbn`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>