package jdbc;

import java.sql.*;

public class JDBCConn { public static void getConn() { /********** Begin / try { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } / End **********/

    /**********    Begin   **********/
    Connection conn = null;
    Statement statement = null;
    //2.建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
    // 127.0.0.1:3306是mysql服务器地址及端口   数据库编码格式设置为utf-8
    //3.建立statement对象
    //4.准备SQL语句:如果数据表存在则删除数据表,然后创建学生信息表
    try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8", "root", "123123");
        statement = conn.createStatement();
        statement.executeUpdate("DROP DATABASE IF EXISTS mydb");
        statement.executeUpdate("CREATE DATABASE mydb");
        statement.executeUpdate("USE mydb");
        statement.executeUpdate("CREATE TABLE student(id INT(11) NOT NULL, name VARCHAR(20), sex VARCHAR(4), age INT(11), PRIMARY KEY(id))");
        ResultSet rs = statement.executeQuery("DESC student");
        while(rs.next()) {
            System.out.println(rs.getString(1) + " " + rs.getString(2));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    /**********    End   **********/
    //5.关闭statement对象和连接对象
    finally {
        try {
            if(statement!=null)
                statement.close();
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
编程要求在右侧编辑器补充代码完成下列相应任务:加载数据库驱动;【平台数据库连接的用户user为root密码password为123123】创建数据库mydb;创建表student。student表结构为:字段名	类型	备注	约束id	int	学生id	非空name	varchar20	学生姓名	无sex	varchar4	学生性别	无age	int	学生年龄	无测试说明平台会对你编写的代码进行测试

原文地址: https://www.cveoy.top/t/topic/fJU1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录