码迷,mamicode.com
首页 > 数据库 > 详细

()java jdbc连接

时间:2018-12-15 13:57:01      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:next   catch   cep   \n   final   tin   result   bsp   statement   

测试使用 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("\n");
            }
            //关闭
            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 jdbc连接

标签:next   catch   cep   \n   final   tin   result   bsp   statement   

原文地址:https://www.cnblogs.com/buchizaodian/p/10122770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!