この記事の例では、JDBC オペレーション データベースを追加、削除、更新、検索する方法について説明します。参考のために皆さんと共有してください。詳細は次のとおりです。
パッケージ cn.com.JDBC;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class CRUD { public static void main(String[] args) throws SQLException { // TODO 自動生成メソッド スタブ //create() //update(); read(); } static void delete() throws SQLException { Connection conn=null; ResultSet resultset=null; // 単一ケースの設計パターン conn=JdbcUtilsSingle.getInstance().getConnection(); //3. ステートメントを作成します st=conn.createStatement(); //4. ステートメント String sql="delete from user where id>5"; int i=st.executeUpdate(sql); 最後に { JdbcUtils.free (resultset, st, conn); } } static void update() throws SQLException { 接続ステートメント st=null; resultset=null; try { //2. 接続を確立します conn=JdbcUtils.getConnection(); // シングルトン設計モード conn=JdbcUtilsSingle.getInstance().getConnection(); //3. ステートメントを作成します。 ( ); //4 ステートメント String sql="update user setmoney=money+20"; を実行します。 i=st.executeUpdate(sql); System.out.println("i="+i); } 最後に { JdbcUtils.free(resultset, st, conn) } } static void create() throws SQLException { 接続 conn= null; ステートメント st=null; ResultSet resultset=null; //2. 接続を確立します。 //単一ケース設計モード conn=JdbcUtilsSingle.getInstance().getConnection(); //3. ステートメントを作成します st=conn.createStatement(); //4. ステートメントを実行します String sql="insert into user(name,birthday,お金) 値('wy','2011-09-23','2894656')"; int i=st.executeUpdate(sql); System.out.println("i="+i); } 最後に { JdbcUtils.free(resultset, st, conn) } } static void read() throws SQLException { 接続 conn= null; ステートメント st=null; ResultSet resultset=null; //2. 接続を確立します。 //単一ケース設計モード conn=JdbcUtilsSingle.getInstance().getConnection(); //3. ステートメントを作成します st=conn.createStatement() //4. ステートメントを実行します set=st.executeQuery("select id,name,誕生日,ユーザーからのお金"); //5. 結果を処理 while(resultset.next()) { System.out.println(resultset.getObject("id")); System.out.println(resultset.getObject("name")); out.println(resultset.getObject("money")); } } 最後に { JdbcUtils.free(resultset, st, conn); } }}パッケージ cn.com.JDBC;インポート java.sql.Connection;インポート java.sql.DriverManager;インポート java.sql.ResultSet;インポート java.sql.SQLException;インポート java.sql.Statement;パブリック クラスJdbcUtils {プライベート静的文字列url="jdbc:mysql://localhost:3306/jdbc"; プライベート静的文字列ユーザー="root"; プライベート JdbcUtils() { } static { .mysql.jdbc.Driver"); } catch(ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } public static void free(ResultSet resultset,Statement st,Connection conn) { //6. リソースを解放します try{ if(resultset!=null) 結果セット.close(); } catch (SQLException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); if(st!=null) st.close(); } catch (SQLException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); }finally { if(conn!=null) try { conn.close( ); } catch (SQLException e) { // TODO 自動生成された catch ブロック e.printStackTrace() } } }}
この記事が Java プログラミングの皆様のお役に立てれば幸いです。