1. 程式人生 > >jdbc-佔位符

jdbc-佔位符

package com.oracle.jdbc.mysql;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;


public class JDBCUtil {
private static String driver = null;
private static String url = null;
private static String user = null;
private static String password = null;


static {
Properties p = new Properties();
try {
p.load(new FileInputStream(new File("jdbc.Properties")));
driver = p.getProperty("driver");
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
} catch (FileNotFoundException e) {
System.out.println("Properties載入失敗");
e.printStackTrace();
} catch (IOException e) {
System.out.println("讀取檔案失敗");
e.printStackTrace();
}
}


public static Connection getConn() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
System.out.println("驅動載入失敗");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("資料庫連線失敗");
e.printStackTrace();
}
return conn;
}


public static void main(String[] args) {
String sql = "select * from cls where cls.id= ? ";
try {
Connection conn =getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 4);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + ":" + rs.getString(2));
}
} catch (SQLException e) {
System.out.println("處理sql資料失敗");
e.printStackTrace();
}


}

}

注意:jdbc.Properties和上篇文章相同