import java.sql.Connection ;import java.sql.DriverManager ;import java.sql.Statement ;public class shiyan4{ public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; public static final String DBURL = "jdbc:mysql://localhost:3306/ace" ; public static final String DBUSER = "root" ; public static final String DBPASS = "root" ; public static void main(String args[]) throws Exception {
Connection conn = null ;
Statement stmt = null ;
Class.forName(DBDRIVER) ;
String sql = "SELECT user_name FROM users;";
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
stmt = conn.createStatement() ;
stmt.executeUpdate(sql) ;
stmt.close() ;
conn.close() ;
}
}
2 回答
Helenr
TA貢獻1780條經驗 獲得超4個贊
剛開始學習java時寫的代碼,oracle的,改成mysql的驅動和對應的用戶名密碼基本就可以了
package cn.database;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import oracle.jdbc.pool.OracleDataSource;public class DataBase { private Connection conn = null; private Statement stmt = null; private ResultSet rs = null; public DataBase() {
// oracle 的jdbc 連接
try { OracleDataSource ds = new OracleDataSource();
ds.setUser("uamqas02");
ds.setPassword("uamqas02");
ds.setURL("jdbc:oracle:thin:@localhost:1521:devdb01");
conn = ds.getConnection();
stmt = conn.createStatement();
} catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
} public ResultSet executeQuery(String sql) {
rs = null; try { // stmt=conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
System.err.println("executeQuerty:" + e.getMessage());
} return rs;
} // ---------------------------數據庫的更新、修改、刪除操作-------------------------------------------------
public boolean executeUpdate(String sql) // 更新方法(增、刪、改)
{ boolean temp = false; try {
stmt = conn.createStatement(); int i = stmt.executeUpdate(sql); if (i >= 1)
temp = true;
} catch (SQLException e) {
e.printStackTrace();
System.err.println("executeUpdate:" + e.getMessage());
} return temp;
} public boolean saveOrUpdateCommit(String sql, String sql2) { boolean temp = true; try {
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.addBatch(sql);
stmt.addBatch(sql2);
stmt.executeBatch();
conn.commit();
} catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace();
temp = false; // 回滾
try {
conn.rollback();
} catch (SQLException e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
} try {
conn.commit();
} catch (SQLException e) { // TODO Auto-generated catch block
temp = false;
e.printStackTrace();
} return temp;
} public void closeStmt() { try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} public void closeConn() { try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}添加回答
舉報
0/150
提交
取消
