zoukankan      html  css  js  c++  java
  • java jdbc连接

    测试使用 jdk-8u191-windows-x64、mysql-8.0.12-winx64、mysql-connector-java-8.0.13.jar

    查询

    import java.sql.*;
    
    public class Main {
    
        //JDBC 驱动名
        //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        //JDBC 连接串
        //static final String DB_URL = "jdbc:mysql://localhost:3306/world";
        static final String DB_URL = "jdbc:mysql://localhost:3306/world?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        // 数据库的用户名与密码
        static final String USER = "root";
        static final String PASS = "Rock3690";
    
        public static void main(String[] args) {
            Connection conn = null;
            Statement stmt = null;
            String sql="SELECT * FROM world.city;";
            try {
                // 注册 JDBC 驱动,
                //Class.forName(JDBC_DRIVER);       
                //连接数据库
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
                //声明
                stmt = conn.createStatement();
                //结果集对象存放查询的数据
                ResultSet rs = stmt.executeQuery(sql);
                //
                while(rs.next()){
                    // 赋值
                    int id  = rs.getInt("id");
                    String name = rs.getString("name");
                    String population = rs.getString("population");
    
                    // 输出
                    System.out.print("ID: " + id);
                    System.out.print(", 城市名称: " + name);
                    System.out.print(", 城市人口: " + population);
                    System.out.print("
    ");
                }
                //关闭
                rs.close();
                stmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

     插入

    public static void main(String[] args) {
            Connection conn = null;
            Statement stmt = null;
            String sql="insert into  Person values (1,'毛不易')";
            try {
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
                stmt = conn.createStatement();
                //
                stmt.executeUpdate(sql);
                stmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  • 相关阅读:
    Java之Chat历程
    Java之静态方法中的内部类
    Java异常捕获之finally
    C语言复杂声明的本质与局限
    使用beyond compare或kompare作为git的对比、合并工具
    [二分] [洛谷] P1258 小车问题
    [STL] [洛谷] P1165 日志分析
    [洛谷] P2802 回家
    卡特兰数的应用
    [洛谷] P1722 矩阵Ⅱ
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/10122770.html
Copyright © 2011-2022 走看看