1.Java 连接mysql数据库,并且实现插入一条数据。

public static void main(String[] args) {
        Statement state=null;
        Connection conn=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
             conn = DriverManager.getConnection("jdbc:mysql:///stu", "root", "123456");
            state = conn.createStatement();
            String sql="insert into acount values(null,'王五',3000)";
            int count = state.executeUpdate(sql);
            if (count>0){
                System.out.println("添加成功");
            }else {
                System.out.println("添加失败");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //避免空指针异常
          if (state!=null){
              try {
                  state.close();
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

 

 

 

更多推荐

Java 连接mysql数据库,并且实现插入一条数据。