0
点赞
收藏
分享

微信扫一扫

向id自增长表插入数据,commit提交

捡历史的小木板 2022-03-19 阅读 43
java
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

在这里插入图片描述
在这里插入图片描述

举报

相关推荐

0 条评论