記事のディレクトリ
A、JDBC概要
Javaデータベース接続:データベース接続は、実行可能なSQL文のAPIです。
JDBCをされインターフェイス指向プログラミング代表的なアプリケーション:リレーショナルデータベースシステムと団結簡素化発展を達成するために、SunはAPIの標準セット(インタフェース)を開発しました(たとえば、MySQLの、DB2、Oracleなど)の多様な種類の、異なるベンダーは、その根拠を実現しますJDBCデータベースプログラム開発、クロスプラットフォームの実行は、ドライバは異なるデータベースを使用する必要があります。
特定のデータベースに接続したときにほとんどのデータベース・システムは、適切なJDBCドライバを持っている、あなたは適切なデータベースドライバを持っている必要があります。
二、(例えばMySQLへ)JDBCプログラミング手順
ジャーパッケージに1、
IDEA、プロジェクトに対応するJDBCドライバのjarパッケージをインポートし、そしてによってadd library
ワークスペースに追加します。
図2に示すように、データベースドライバをロードします
負荷データベースドライバ、一般的に使用されるクラスのクラスforName(驱动类全类名)
ローディング駆動、例えば、ロードされたMySQLを駆動する方法であって
Class.forName("com.mysql.jdbc.Driver");
最新のJDBCドライバクラスドライバが自動的にこのケース/サービスディレクトリ内のMETA-INFジャーの下で、SPIによって登録されていることに注意してくださいので、に、java.sql.driverファイルに指定されたJDBCドライバクラスが含まれていますこの場合、実際には、この工程を省略することができます。
3、DriverManagerのConnectionオブジェクトによって得られました
使用するDriverManager
静的メソッドのクラスをpublic static Connection getConnection(String url,String user, String password)
接続オブジェクトの接続を取得します。
引数:データベースのURL、ユーザ名、ユーザ、パスワードはpasswordです。
-
データベースのURLを書くの道:
jdbc:mysql://服务器名或IP地址:端口号/数据库名[?参数名=参数值]
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
-
サーバーは、MySQLにローカルである場合は、次のように省略することができます。
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb2", "root", "123456");
另外getConnection还有个重载方法:public static Connection getConnection(String url,java.util.Properties info)
,将user和password存储到Properties对象中,传入方法即可。
Properties prop = new Properties();
prop.setProperty("user","root");
prop.setProperty("password","123456")
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2",prop);
3、定义SQL语句
String sql = "update orders set price = 500 where id = 1";//普通的sql语句
//如果需要执行某些相似的sql语句多次,只有某个地方有改动,可以使用带占位符的sql语句
String sql = "select * from user where username = ? and password = ?";//带占位符的sql语句
4、利用Connection创建Statement对象
//创建最基本的Statement对象
Statement statement = conn.createStatement();
//创建一个预编译sql语句的PreparedStatement对象,后者是前者的子接口。使用时需要将sql语句占位符部分进行填充。
PreparedStatement prs = conn.prepareStatement(sql);
Statement与PreparedStatement:
-
在执行多次相似的sql语句时,PreparedStatement预编译SQL语句性能更好。
-
PreparedStatement无需凭借SQL语句,编程更加简单(ps:确实简单)。
-
PreparedStatement可以防止SQL注入。
//SQL注入的例子: String sql = "select * from user where username = '"+username+"'and password = '"+password+"'"; resultSet = statement.executeQuery(sql); return resultSet.next();
当我用Statement对象执行拼接完成之后的SQL语句,目的是为了判断是否传入正确的用户名和密码。这时,如果随便输入不存在的用户名
dede
,密码输入:' or true or '
,这时SQL注入之后就会变成下面这个鬼样子:select * from user where username = 'dede'and password = ''or true or '';
相当于直接输入了true,非常不合理,而PreparedStatement可以避免SQL注入:
//PreparedStatement防止SQL注入 String sql = "select * from user where username = ? and password = ?"; preparedStatement.setString(1,username); preparedStatement.setString(2,password); resultSet = preparedStatement.executeQuery();
5、利用Statement执行SQL语句
无论是Statement还是它的子接口对象,都拥有执行SQL语句的方法,下面是比较重要的几个:
- boolean excute():可以执行任何的SQL语句,但是比较麻烦,通常不用。(这个方法在子接口里是没有的嗷),如果部清楚SQL语句的类型,可以使用该方法。
- int executeUpdate():用于执行DML和DDL语句,返回结果是受影响的行数。
//定义sql语句
String sql = "update orders set price = 500 where id = 1";
//获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//执行sql
int count = stmt.executeUpdate(sql);
- ResultSet executeQuery():只能执行查询语句,返回结果是一个ResultSet结果集。
PreparedStatement preparedStatement = null;
//定义sql语句
String sql = "select * from user where username = ? and password = ?";
//获取PreparedStatement对象
preparedStatement = conn.prepareStatement(sql);
//给对应的占位符赋值,如果不清楚参数类型可以使用setObject()传入参数
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
//执行查询语句,获取结果集
ResultSet resultSet = preparedStatement.executeQuery();
6、操作ResultSet对象
明确一点,ResultSet对象是通过excuteQuery
执行查询语句的结果。原理类似于迭代器,通过指针的移动来获取值。
典型的方法:
-
次の():最初の行に開始ポインタポイントは、ポインタが下方に移動する前に、バックの代わりに記録は、無戻り偽、真が返すかどうか、それは、ブール値を返します。そのため、直接可能な記録が存在するか否かを判断する
ResultSet.next();
判断。 -
getXXX():取得する指定した行の値は、特定の列。多くのオーバーロードされた方法がある含む:(として、1から始まる列の指定された数を渡し
getInt(1)
、(例えば、パス列名、指定されたパラメータ最初の列ラインINT値の代表)getInt("id")
流用idフィールドの値を取得します)。
//打印所有记录
while(resultSet.next()) {
//获取数据
int id = resultSet.getInt(1);
String product = resultSet.getString("product");
int price = resultSet.getInt("price");
System.out.println(id + "--" + product + "--" + price);
}
7、データベースの回復資源
2つの方法でデータベースリソースの回復:
接続、ステートメント、ResultSetの継承AutoCloseableインタフェースのJava7使用することができる自動シャットリソースをクローズするステートメントを試してみてください。try-with-resources
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb2", "root", "123456");
Statement stmt = conn.createStatement())
{
String sql = "update orders set price = 500 where id = 1";
int count = stmt.executeUpdate(sql);
System.out.println(count);
}
}
伝統的な試み...... catchステートメントがあります:
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb2", "root", "123456");
stmt = conn.createStatement();
String sql = "update orders set price = 500 where id = 1";
int count = stmt.executeUpdate(sql);
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//避免空指针异常
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
参考:「狂気のJava配布資料」