标签:ps String prop 插入 sql commit null id con
不要忘写了 con.commit();,否则数据库没变化!!
ps.setString(1, “lisi”);id自增长,不用设置,设置数和?数一致
package com.heima.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class InsertTest {
public static void main(String[] args) throws SQLException {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("xx.properties");
prop.load(fis);
String driverClass = prop.getProperty("driverClass");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driverClass);
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
String sql = "insert into login1 values(null,?,?)";
ps = con.prepareStatement(sql);
System.out.println("?个数是" + ps.getParameterMetaData().getParameterCount());
//id的不用设置了,自增长
ps.setString(1, "lisi");
ps.setString(2, "456");
System.out.println("sql = " + sql);
int update = ps.executeUpdate();
System.out.println("update = " + update);
System.out.println("sql = " + sql);
//不要忘写了,否则数据库没变化!!
con.commit();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
con.rollback();
System.out.println("插入错误");
e.printStackTrace();
}
finally{
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
xx.properties
在项目文件夹下,不是src下!
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user_manager
user=root
password=root
标签:ps,String,prop,插入,sql,commit,null,id,con 来源: https://blog.csdn.net/djydjy3333/article/details/123592388
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。