用java写一个跟mysql连接的代码,并且可以插入mysql中表的数据
时间: 2023-12-03 07:43:58 浏览: 28
可以使用Java中的JDBC来连接MySQL并插入数据。下面是一个简单的示例代码:
```java
import java.sql.*;
public class MySQLExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("插入数据...");
stmt = conn.createStatement();
String sql = "INSERT INTO student (name, age) VALUES ('Tom', 18)";
stmt.executeUpdate(sql);
// 完成后关闭
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch (Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
注意:在上面的代码中,需要将`test`替换为你自己的数据库名,`root`替换为你自己的用户名,`password`替换为你自己的密码,`student`替换为你自己的表名,`name`和`age`替换为你自己的表结构。