JDBC

来源:互联网 发布:模具erp软件 编辑:程序博客网 时间:2024/05/17 08:19

Connection con = null;
PreparedStatement ps = null;
try {
// 加载驱动,将指定驱动完成加载,从而初始化静态变量和静态块
Class.forName(“org.gjt.mm.mysql.Driver”);

        // 建立连接,其中mytest为连接mysql的库名,root是mysql的登录用户名,lovo为mysql的登录密码        // con = DriverManager        // .getConnection(        // "jdbc:mysql://localhost:3306/mytest?characterEncoding=utf-8",        // "root", "111");        // localhost表示连接主机名,代表本机的ip地址        con = DriverManager                .getConnection("jdbc:mysql://localhost:3306/mytest?characterEncoding=utf-8");        con = DriverManager                .getConnection(                        "jdbc:mysql://localhost:3306/mytest?characterEncoding=utf-8",                        "root", "111");        // 执行sql语句,得到PreparedStatement数据库操作对象        // 添加        // ps        // =con.prepareStatement("insert into t_product(productName,price,createTime,factory) values(?,?,?,?)");        ps = con.prepareStatement("insert into t_product(productName,price,createTime,factory) value(?,?,?,?)");        // 填充占位符,1表示第几个?,第二个参数表示将什么内容插入到第一个?的位置        ps.setString(1, bean.getName());        ps.setDouble(2, bean.getPrice());        ps.setDate(3, bean.getCreateTime());        ps.setString(4, bean.getFactory());        // // 更新数据库,将内容真正写入数据库        ps.executeUpdate();    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            ps.close();            con.close();        } catch (SQLException e) {            e.printStackTrace();        }    }
0 0