最近在学习mysql简单的增删改查,然后根据网上的一些教程通过jdbc对数据库进行了操作,现在把编写的一个类源码发出来,做学习交流。
package jdbc;
import java.sql.*;
public class MysqlDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASS = "root123";
public static void main(String[] args) {
String sql = "select id,name,sex,age from students";
String sql2 = "update students set age=age+3";
MysqlDemo mysqlDemo = new MysqlDemo();
mysqlDemo.getConn();
try {
mysqlDemo.select(sql);
mysqlDemo.operateMysql(sql2);
System.out.println();
mysqlDemo.select(sql);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Goodbye");
}
public Connection getConn() {
Connection conn = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void select(String sql) throws SQLException {
Connection conn = getConn();
Statement stmt = conn.createStatement()
ResultSet result = stmt.executeQuery(sql);
while (result.next()) {
System.out.print("id: " + result.getInt("id"));
System.out.print(" name: " + result.getString("name"));
System.out.print(" sex: " + result.getString("sex"));
System.out.println(" age: " + result.getInt("age"));
}
result.close();
stmt.close();
conn.close();
}
public void operateMysql(String sql) throws SQLException {
Connection conn = getConn();
Statement stmt = conn.createStatement();
stmt.execute(sql);
stmt.close();
conn.close();
}
}