数据库插入操作-java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SqlDemo {

    public static void main(String[] args) {
        try {
            //1、载入驱动程序  
                //驱动程序名称: com.mysql.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver");
            //2、建立和数据库的连接
                //sql用户名称:root 
                //sql用户密码:root
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/store?characterEncoding=utf8&useSSL=false", "root", "root");
                //(2)插入操作:
            String sql = "insert into good_list values(?,?)";
                /* 百度说:
                java,servlet中的PreparedStatement 接口继承了Statement,
                并与之在两方面有所不同:有人主张,在JDBC应用中,如果你已经是稍有水平开发者,
                你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement。
                */
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setInt(1, 14);//插入int类型数据
            pst.setString(2, "插入String类型数据");
            //成功返回1,并赋值给result
            int result = pst.executeUpdate();
            //添加信息结果处理
            if(result == 1){
                System.out.println("数据库添加信息成功");
            }else {
                System.out.println("数据库添加信息不成功哦!!");
            }
            //关闭
            pst.close();
            con.close();
        
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
    }

}
原文地址:https://www.cnblogs.com/suxiaoxia/p/6680158.html