java 操作数据库
package foo;
import java.sql.*;
public class JdbcDemo {
private static Connection conn;
private static Statement ps;
private static ResultSet rs;
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://xx.xx.xx.xx:port/SOFTWARE_APP?user=SOFTWARE_APP&password=software&characterEncoding=gbk";
private static final String USER ="xxx";
private static final String PASS = "xxx";
public JdbcDemo() {
JdbcDemo.getConnection();
}
public static Connection getConnection() {
System.out.println("连接中...");
try {
try {
Class.forName(JdbcDemo.DRIVER).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
conn = DriverManager.getConnection(JdbcDemo.URL);
System.out.println("成功连接");
}catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(String sql) {
System.out.println("执行SQL语句中...");
try {
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
if(sql.substring(0, 6).equals("select")){
rs = ps.executeQuery(sql);
System.out.println("执行完查询操作,结果已返回ResultSet集合");
}else if(sql.substring(0, 6).equals("delete")){
ps.executeUpdate(sql);
System.out.println("已执行完毕删除操作");
}else if(sql.substring(0, 6).equals("insert")){
ps.executeUpdate(sql);
System.out.println("已执行完毕增加操作");
}else{
ps.executeUpdate(sql);
System.out.println("已执行完毕更新操作");
}
}catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println("查询结果为:");
return rs;
}
public static void closeConnection(){
System.out.println("关闭连接中...");
try {
if (rs != null) {
rs.close();
System.out.println("已关闭ResultSet");
}
if (ps != null) {
ps.close();
System.out.println("已关闭Statement");
}
if (conn != null) {
conn.close();
System.out.println("已关闭Connection");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) {
JdbcDemo demo = new JdbcDemo();
demo.getConnection();
// String sql = "delete from type where id = 1";
// String sql_1 = "insert into type values(1, '教学设备')";
String sql_2 = "select * from software_item limit 1;";
// demo.getStatement(sql);
// demo.getStatement(sql_1);
demo.getStatement(sql_2);
ResultSet rs = demo.getResultSet();
try {
while(rs.next()) {
System.out.println("" + rs.getInt(1) + " ");
System.out.println(rs.getString(2));
System.out.println(rs.getInt(3));
}
}catch (SQLException e) {
e.printStackTrace();
}
demo.closeConnection();
}
}