您的位置:首页 > 其它

JDBC简单的增删改查

2017-09-08 12:05 99 查看
最近在学习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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: