JAVA-JDBC接続および関連する学習

JAVA-JDBC接続および関連する学習

JDBCの基本的な接続方法

まず、Mysqlまたはその他のデータベースをダウンロードしてインストールする準備をしてから、mysql-connector-java-5.0.8-bin.jarまたはその他のサードパーティパッケージ(ドライバー用)をインポートします。

次に接続します:

	Connection connection = null;
	PreparedStatement preparedStatement = null;
	//第一步加载驱动;
Class.forName("com.mysql.jdbc.Driver");
 	//第二步获取连接;
// 建立与数据库的Connection连接
// 这里需要提供:
// 数据库所处于的ip:127.0.0.1 (本机)本地可以写local:
// 数据库的端口号: 3306 (mysql专用端口号)
// 数据库名称 weeklyreport
// 编码方式 UTF-8
//serverTimezone最好加一下,因为有时候会报错;
//useSSL=false
//MySQL在高版本需要指明是否进行SSL连接
//1.true 需要连接
//2.false 不需要连接
String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";//自己的密码
			connection = DriverManager.getConnection(url, user, password);
	//创建statement或者preparedStatement,先用preparedStatement举例;
	String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setString(2, password2);
			preparedStatement.setString(3,date);
			preparedStatement.executeUpdate();
	//这就实现了一个插入注册信息的操作
	//最后一步要实现关闭connection和preparedStatement操作;
	connection.close();
	preparedStatement.close();

完全な

Connection connection = null;
PreparedStatement preparedStatement = null;
try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";//自己的密码
			connection = DriverManager.getConnection(url, user, password);
			String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setString(2, password2);
			preparedStatement.setString(3,date);
			preparedStatement.executeUpdate();
			}catch (ClassNotFoundException e) {
    
    
				 e.printStackTrace();
			} catch (SQLException e){
    
    
				 e.printStackTrace();
			} finally {
    
    
				try {
    
    
                    //一般preparedStatement关闭在connection关闭之后;
					connection.close();
					preparedStatement.close();
				} catch (SQLException e){
    
    
					 e.printStackTrace();
				}
			}
	}

SQLステートメント

1. SQLには、追加、削除、変更、チェックなど、他の多くの操作があります

//增加
 String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
//删除 
 String sql = "delete from hero where id = 5";
//更改
 String sql = "update hero set name = 'name 5' where id = 3";

その他の特定の操作については、新人チュートリアルmysqlのステートメントの特定の使用法を参照してください。

2.より特別なものはクエリ操作です。

public boolean finduser(String name2,String password2) {
    
    
		ResultSet result = null;
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		int i =0;
		try {
    
    
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";
			connection = DriverManager.getConnection(url, user, password);
			String sql = "select * from users2 where USER_NAME= ? and USER_PASSWORD= ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name2);
			preparedStatement.setString(2, password2);
            //特殊的就是要设置一个结果集ResultSet,把结果存放在结果集中,
			result =preparedStatement.executeQuery();
			while(result.next()) {
    
    
				i++;
			 }
            //这里实现的功能就是在登陆的时候验证账号和密码,如果正确,那查询得到的结果集就有内容并i++最后返回true;
			}catch (ClassNotFoundException e) {
    
    
				 e.printStackTrace();
			} catch (SQLException e){
    
    
				 e.printStackTrace();
			} finally {
    
    
				try {
    
    
					connection.close();
					preparedStatement.close();
					result.close();
                    //关闭结果集
				} catch (SQLException e){
    
    
					 e.printStackTrace();
				}
			}
		if (i == 0)
			return false;
		else 
			return true;
	}

その他の特定の操作については、新人チュートリアルmysqlのステートメントの特定の使用法を参照してください。

StatementとpreparedStatementの違い

1、

ステートメントには、文字列の連結、読みやすさ、および保守性の悪さが必要です。

PreparedStatementパラメータ設定、読み取り可能、間違いやすい;

			Statement s = connection.createStatement();
            PreparedStatement  preparedStatement= connection.prepareStatement(sql);
            // Statement需要进行字符串拼接,可读性和维修性比较差
            String sql0 = "insert into USERS1(null," + "'学生1'" + "," + "'123456'"+")";
            s.execute(sql0);
            String sql = "insert into USERS1(null,?,?,?)";
            // PreparedStatement 使用参数设置,可读性好,不易犯错
            // "insert into USERS1(null,?,?)";
            preparedStatement.setString(1, "学生1");
            preparedStatement.setString(2, "123456");
            preparedStatement.execute();

2. PreparedStatementには事前コンパイルメカニズムがあり、パフォーマンスはステートメントよりも高速です

データベースは?を使用してSQLをプリコンパイルします

実行するたびに、パラメータをデータベースに転送するだけで済みます

  1. ネットワーク送信量がステートメントよりも小さい
  2. データベースをコンパイルする必要がなく、応答が速くなります

3. PreparedStatementは、SQLインジェクション攻撃を防止します。たとえば、ログイン時にパスワードがOR 1 = 1に追加されると、SQLによって読み取られ、ログインされます。

executeとexecuteUpdateの違い

1. executeexecuteUpdateの類似点:どちらも追加、削除、変更できます

preparedStatement.execute();
preparedStatement.executeUpdate();

2.異なる:
executeはクエリステートメント
実行でき、 getResultSetを介して結果セットが取り出され、
executeUpdateはクエリステートメントを実行できません。
異なる2:
executeはブール型を返し、trueはクエリステートメントが実行されることを意味し、falseは挿入、削除、更新などを意味します。
executeUpdateがintを返すのを待ち、影響を受けたデータの数を示します

事務

  			connection.setAutoCommit(false);
  
            // 更改操作
            String sql1 = "update hero set hp = hp +1 where id = "xuesheng1"";
            statement.execute(sql1);
  
         
           //第二个更新操作 
           // 不小心写错写成了 updata(而非update)
            String sql2 = "updata users1 set score = score -1 where name = "xuesheng2"";
            statement.execute(sql2);
  
            // 手动提交
            connection.commit();

だから置く

connection.setAutoCommit(false);

connection.commit();

1つの操作間のトランザクションにエラーがある限り、エラーが発生しないように続行されません。

ヘビ

実際、プロパティがデータベースにレコードを格納できるオブジェクトを作成してから、操作を展開することです。

ORM =オブジェクト関係データベースマッピング

オブジェクトとリレーショナルデータベースのマッピング

簡単に言えば、オブジェクトはデータベース内のレコードに対応します

DAO

実際、ORMのアイデアは、このクラスのデータベース関連の操作をカプセル化するために使用され、JDBCコードは他の場所では見ることができません。

データベース接続プール

事前にいくつかの接続を作成し、スレッドがそれらを使用するのを待ちます。それらがすべて使用される場合、未使用のスレッドは接続がなくなるのを待ってデータベース接続プールに戻ります。これらの接続は閉じられませんが、継続的にリサイクルされるため、継続的にリサイクルされます。接続を開始および閉じる時間を節約します。

package jdbc;
  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
  
public class ConnectionPool {
    
    
  
    List<Connection> cs = new ArrayList<Connection>();
  
    int size;
  
    public ConnectionPool(int size) {
    
    
        this.size = size;
        init();
    }
  
    public void init() {
    
    
          
        //这里恰恰不能使用try-with-resource的方式,因为这些连接都需要是"活"的,不要被自动关闭了
        try {
    
    
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < size; i++) {
    
    
                Connection c = DriverManager
                        .getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
  
                cs.add(c);
  
            }
        } catch (ClassNotFoundException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  
    public synchronized Connection getConnection() {
    
    
        while (cs.isEmpty()) {
    
    
            try {
    
    
                this.wait();
            } catch (InterruptedException e) {
    
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Connection c = cs.remove(0);
        return c;
    }
  
    public synchronized void returnConnection(Connection c) {
    
    
        cs.add(c);
        this.notifyAll();
    }
  
}
//代码来自how2j网站


おすすめ

転載: blog.csdn.net/jnh1234/article/details/109425961