()java jdbc连接
Posted 富坚老贼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了()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 jdbc连接的主要内容,如果未能解决你的问题,请参考以下文章