public class createDemo1 {
public static void main(String[] args) throws Exception {
operateMysqlTool o = operateMysqlTool.getObject();
//连接数据库
o.connection("jdbc:mysql:///person", "root", "");
// 查询
o.query("select good_id,good_name,good_number from mygood");
o.result("good_id", "good_name", "good_number");
// 插入入数据
// o.update("insert into mygood values(null,'kkk',23)");
// 删除数据
// o.update("delete from mygood where good_id=6");
// 更新数据
// o.update("update mygood set good_name='s4' where good_id=3");
// 释放资源
// o.close();
}
}
工具类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* 数据库操作的工具类,单例设计模式
*@author 廖永祥
*2017.5.14
*
*/
public class operateMysqlTool {
/*
* 静态代码块, 驱动加载一次即可;
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private operateMysqlTool() {
}
private static operateMysqlTool o = new operateMysqlTool();
public static operateMysqlTool getObject() {
return o;
}
private Connection c = null;
private Statement s = null;
private ResultSet rs = null;
/*
* 连接
*/
public void connection(String url, String user, String password) {
try {
c = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 执行查询
*
*/
public void query(String str) {
try {
s = c.createStatement();
rs = s.executeQuery(str);
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 结果的处理 ,可变参数方便查询;
*/
public void result(String... str) {
try {
while (rs.next()) {
for (String i : str) {
System.out.print(rs.getObject(i) + "--");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 更新(插入/删除/新增)数据
*
*/
public void update(String sql) {
int i = 0;
try {
s = c.createStatement();
i = s.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
if (i == 1) {
System.out.println("操作成功!");
} else
System.out.println("操作失败!");
}
/*
* 释放资源
*/
public void close() {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
数据表: