- import java.sql.SQLException;
- /**
- * 数据库访问 MySQL.
- *
- * @author yuzi
- * @version
- */
- public class T {
- public static void main(String[] args) {
- // 1. 注册驱动
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }// Mysql 的驱动
- // 先定义变量,后使用和关闭
- java.sql.Connection conn = null;// 数据库连接
- java.sql.Statement stmt = null;// 数据库表达式
- java.sql.ResultSet rs = null;// 结果集
- try {
- // 2. 获取数据库的连接
- conn = java.sql.DriverManager
- .getConnection(
- "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK",
- "root", null); // root是用户名,密码为空
- // 3. 获取表达式
- stmt = conn.createStatement();
- // 执行插入数据的 SQL
- stmt
- .executeUpdate("insert into Student(username, password,age) values('张三', '1234', 20)");
- // 4. 执行 SQL
- rs = stmt.executeQuery("select * from Student");
- // 5. 显示结果集里面的数据
- while (rs.next()) {
- System.out.println("编号=" + rs.getInt(1));
- System.out.println("学生姓名=" + rs.getString("username"));
- System.out.println("密码=" + rs.getString("password"));
- System.out.println("年龄=" + rs.getString("age"));
- }
- // 执行删除数据的 SQL
- // stmt.executeUpdate("delete from Student");
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
- try {
- rs.close();
- } catch (SQLException e) {
- }
- try {
- stmt.close();
- } catch (SQLException e) {
- }
- try {
- conn.close();
- } catch (SQLException e) {
- }
- }
- }
- }
CREATE TABLE Student (
id int NOT NULL auto_increment,
username varchar(200) NOT NULL,
password varchar(20) NOT NULL,
age int,
PRIMARY KEY (id)
)