JDBC纯驱动方式连接MySQL
时间:2021-07-01 10:21:17
帮助过:11人阅读
- package com.abc;
-
-
-
- importjava.sql.DriverManager;
-
- importjava.sql.ResultSet;
-
- importjava.sql.SQLException;
-
- importjava.sql.Connection;
-
- importjava.sql.Statement;
-
-
-
- publicclass MysqlDemo {
-
- publicstaticvoid main(String[] args) throws Exception {
-
- Connection conn = null;
-
- String sql;
-
-
-
-
-
- String url = "jdbc:mysql://localhost:3306/test?"
-
- + "user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
-
- try {
-
-
-
-
-
- Class.forName("com.mysql.jdbc.Driver");
-
-
-
-
-
-
-
-
-
- System.out.println("成功加载MySQL驱动程序");
-
-
-
- conn = DriverManager.getConnection(url);
-
-
-
- Statement stmt = conn.createStatement();
-
- sql = "createtable student(NO char(20),name varchar(20),primary key(NO))";
-
- intresult = stmt.executeUpdate(sql);
-
- if (result != -1) {
-
- System.out.println("创建数据表成功");
-
- sql = "insert into student(NO,name) values(‘2016001‘,‘刘大‘)";
-
- result = stmt.executeUpdate(sql);
-
- sql = "insert into student(NO,name) values(‘2016002‘,‘陈二‘)";
-
- result = stmt.executeUpdate(sql);
-
- sql = "select * from student";
-
- ResultSet rs = stmt.executeQuery(sql);
-
- System.out.println("学号\t姓名");
-
- while (rs.next()) {
-
- System.out.println(rs.getString(1)+ "\t" + rs.getString(2));
-
- }
-
- }
-
- } catch(SQLException e) {
-
- System.out.println("MySQL操作错误");
-
- e.printStackTrace();
-
- } catch (Exception e) {
-
- e.printStackTrace();
-
- } finally {
-
- conn.close();
-
- }
-
- }
-
- }
运行结果:
JDBC纯驱动方式连接MySQL
标签:man 创建 格式 static nbsp except 解压 string try