zoukankan      html  css  js  c++  java
  • JDBC

    package com.example.springboot;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class Demo {
        /**
         * 执行DDL语句(创建表)
         */
    
        public static void main(String[] args) {
            String url = "jdbc:mysql://localhost:3306/mysql?useUnicode=true&serverTimezone=UTC";
            String user = "root"; //用户名
            String password ="123456"; //密码
            Statement stmt = null;
            Connection conn = null;
            try{
                //1.驱动注册程序
                java.sql.Driver driver=new com.mysql.jdbc.Driver();
                DriverManager.registerDriver(driver);
    
                //2.获取连接对象
                conn = DriverManager.getConnection(url, user, password);
    
                //3.创建Statement
                stmt = conn.createStatement();
    
                //4.准备sql
                String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";
    
                //5.发送sql语句,执行sql语句,得到返回结果
                int count = stmt.executeUpdate(sql);
    
                //6.输出
                System.out.println("影响了"+count+"行!");
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }finally {
                //7.关闭连接(顺序:后打开的先关闭)
                if(stmt!=null)
                    try {
                        stmt.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    }
                if(conn!=null)
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    }
            }
        }
    }
    Jdbc程序中的Connection,它用于代表数据库的链接,Connection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的,这个对象的常用方法:
    createStatement():创建向数据库发送sql的statement对象。
    prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
    prepareCall(sql):创建执行存储过程的CallableStatement对象。 
    setAutoCommit(boolean autoCommit):设置事务是否自动提交。 
    commit() :在链接上提交事务。
    rollback() :在此链接上回滚事务。

     输入shou tables;查看表student是否添加成功,可以看到表是添加成功了的

     输入 desc student;查看表结构是否为创建的那一个,符合预期。

  • 相关阅读:
    GAMBIT、ICEM、HYPERMESH耦合面的处理方法
    如何用hypermesh生成包含interface的流体网格
    python求数字位数的方法
    drawPython
    Python入门计划
    书法与篆刻创作结课
    易忽视的Python知识点
    Ubuntu中,wxpython的TextCtrl引发的error:_pixman_log_error
    在Ubuntu15.10中,使用wxPython的webview和JS进行交互
    PyCharm导入tensorflow包
  • 原文地址:https://www.cnblogs.com/yfstudy/p/13602088.html
Copyright © 2011-2022 走看看