()java jdbc连接
时间:2021-07-01 10:21:17
帮助过:46人阅读
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