zoukankan      html  css  js  c++  java
  • JDBC向数据库中写数据

     1 package MYSQK;
     2 import java.sql.*;
     3 
     4 /**
     5  * PreparedStatement 对象可以对sql语句进行预编译,预编译的信息会存在存储该对象中,当相同的sql语句再次执行时,程序
     6  *   会使用PrepareStatement对象中,而不需再次编译去查询数据库,大大提高了数据的访问效率
     7  */
     8 
     9 public class Insert {
    10     public  static  void main(String[] args) throws SQLException{
    11         Connection conn=null;
    12         PreparedStatement pst =null;
    13 
    14         try {
    15             // 1 加载驱动类
    16             Class.forName("com.mysql.jdbc.Driver");
    17             // 2 通过DriverManager获取connection对象
    18              String url="jdbc:mysql://192.168.64.128:3306/jdbc?" +
    19                       "user=root&password=815qza&useUnicode=true&characterEncoding=UTF8";
    20              conn = DriverManager.getConnection(url);
    21              if (!conn.isClosed()){
    22                  System.out.println("Succeeded connecting to the Database!");
    23              }else{
    24                  System.out.println("Sorry,failed  connecting to the Database");
    25              }
    26              // 3 获取pre对象
    27               String sql = "INSERT  INTO  USERS(name,PASSWORD,email,birthday) VALUES (?,?,?,?)";
    28                pst = conn.prepareStatement(sql);
    29              //为sql参数赋值
    30                pst.setString(1,"bowen5");
    31                pst.setString(2,"815qza");
    32                pst.setString(3,"bowen815@126.com");
    33                pst.setString(4,"1990-11-01");
    34              //4  使用prepare对象执行sql语句
    35                int count = pst.executeUpdate();
    36                System.out.println("影响数据库的条数为:"+count);
    37              //5 操作result结果集
    38         }catch (ClassNotFoundException e){
    39             e.printStackTrace();
    40         }finally {
    41             // 6 关闭连接
    42              pst.close();
    43              conn.close();
    44         }
    45     }
    46 }
  • 相关阅读:
    jna学习---windows下一个完整调用
    ndk ffmpeg
    POJ_3264_Interval Tree 最大最小值之差
    ROBY_筛选法求素数 与 打表 学习, 试验可以开的数组大小, 10位int数组
    POJ_2186_Tarjan Popular_Cows
    POJ_1961 KMP next的典型应用 类似于 poj2406
    HDOJ_1711_KMP 求匹配位置
    POJ_2312_BFS:priority_queue -- Battle City
    POJ_1915_Double BFS Knight Moves
    POJ_3414_BFS pots
  • 原文地址:https://www.cnblogs.com/moomcake/p/11831910.html
Copyright © 2011-2022 走看看