Java jdbc连接数据库 INSERT插入
-
package com.edu;
-
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.PreparedStatement;
-
import java.sql.SQLException;
-
-
public
class jdbcTest {
-
-
public static void main(String[] args) {
-
try {
-
Class.forName(
"com.mysql.jdbc.Driver");
//加载驱动程序
-
String url =
"jdbc:mysql://localhost:3306/test";
//定义连接字符串url test是数据库名称
-
Connection conn =DriverManager.getConnection(url,
"root",
"root");
//与数据库连接
-
String sql=
"insert into users(name,sex,age,addr) values(?,?,?,?)";
//sql语句
-
PreparedStatement pstmt=conn.prepareStatement(sql);
//获得预置对象
-
pstmt.setString(
1,
"lili");
//设置占位符的值
-
pstmt.setString(
2,
"女");
-
pstmt.setInt(
3,
21);
-
pstmt.setString(
4,
"西南石油大学");
-
-
int res=pstmt.executeUpdate();
//执行sql语句
-
if(res>
0){
-
System.out.println(
"数据录入成功");
-
}
-
pstmt.close();
//关闭资源
-
conn.close();
//关闭资源
-
-
-
}
catch (SQLException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
catch (ClassNotFoundException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
}
-
-
}
表结构
执行成功后:
原文地址https://blog.csdn.net/Bancroft_boy/article/details/81143202