在JDBC操作(1)文章中介绍了如何通过JDBC驱动连接mysql数据库。本文要介绍通过Java程序执行数据库的更新与查询语句。
首先要完成前期操作,在数据库'mydb'中创建表格'users'。
CREATE TABLE users(
u_id INT PRIMARY KEY AUTO_INCREMENT,
u_name VARCHAR(8) NOT NULL,
u_age INT NOT NULL,
u_sex VARCHAR(2) NOT NULL,
u_height FLOAT(4,1) NOT NULL,
birthday DATE NOT NULL
)ENGINE=INNODB DEFAULT CHARSET = utf8;
为了充分体现Java面向对象的特点,首先定义一个Jdbc类,之后就可以通过创建Jdbc对象来访问mysql数据库。
class Jdbc {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/";
private static final String USER = "root";
private static final String PASS = "****";
private Connection connection;
private Statement statement;
private String dbName;// 所要连接的数据库名称
public Jdbc(String dbName) {
this.dbName = dbName;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL + this.dbName, USER, PASS);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}