標籤:io ar os java for 資料 on cti bs
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();
}
}
java 操作資料庫