编写java程序实现连接mysql数据库,并向数据库test中的student表中插入('08001','武松','男',18,'数学系')这条记录,用Java语言实现
时间: 2024-01-11 22:04:11 浏览: 17
请确保已经安装了MySQL数据库,并且在MySQL数据库中创建了test数据库和student表。
下面是Java代码示例:
```java
import java.sql.*;
public class InsertStudent {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "123456";
String sql = "INSERT INTO student(id, name, gender, age, department) VALUES('08001', '武松', '男', 18, '数学系')";
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate(sql);
System.out.println(rows + " rows inserted.");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用Java的JDBC API连接MySQL数据库,并且执行了一条INSERT语句将数据插入到student表中。其中,url、username和password分别表示连接MySQL数据库的URL、用户名和密码;sql表示要执行的SQL语句;conn表示连接对象,stmt表示语句对象。
运行以上代码后,你可以在MySQL数据库中的student表中查看到新插入的记录。