用到的包:java.sql包
示例代码:
public class IUDData {
private static String jdbcName = "com.mysql.jdbc.Driver";
// 数据库协议地址
private static String dbUrl = "jdbc:mysql://localhost:3306/sunbeam";
// 数据库用户名
private static String dbUser = "root";
// 数据库密码
private static String dbPassword = "root";
// 数据添加操作
private static void addData() {
try {
// 加载数据库驱动
Class.forName(jdbcName);
System.out.println("数据库驱动加载成功!");
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 连接数据库
conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
System.out.println("数据库连接成功!");
// 执行SQL语句
pstmt = conn.prepareStatement("insert into t_test values(?,?,?)");
pstmt.setInt(1, 110);
pstmt.setString(2, "张三");
pstmt.setString(3, "1,3,5,7,9");
int result = pstmt.executeUpdate();
if (result == 1) {
System.out.println("数据插入成功!");
} else {
System.out.println("数据插入失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败!");
} finally {
try {
// 关闭数据库
if (pstmt != null) {
pstmt.close();
if (conn != null) {
conn.close();
System.out.println("数据库关闭成功!");
}
} else {
System.out.println("数据库关闭失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库关闭失败!");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库驱动加载失败!");
}
}
public static void main(String[] args) {
addData();
}
}