JDBC编程大致需如下步骤;
1.加载数据库驱动
//加载驱动
Class.forName(driverClass);
2.通过DriverManager获取数据库连接
//获取数据库连接
Connection conn = DriverManager.getConnection(String url,String user,String pass);
3.通过Connection对象创建Statement对象
//创建Statement对象
Statement stmt=conn.createStatement();
4.使用Statement执行SQL语句
//使用Statement进行查询并返回结果集ResultSet
ResultSet rs=stmt.executeQuery(sql);
5.操作结果集(仅限查询类语句)
while (rs.next()) {
for(int i=0;i<columnCount;i++) {
System.out.println(rs.getString(i+1)+"\t");
}
System.out.println("\n");
}
package jdbc;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
/**
* Created by John on 2017/8/29.
*/
public class ExecuteSQL {
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception {
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
public void executeSql(String sql) throws Exception {
Class.forName(driver);
try (
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt=conn.createStatement()
) {
boolean hasResultSet = stmt.execute(sql);
if (hasResultSet) {
try (
ResultSet rs = stmt.getResultSet()
) {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
for(int i=0;i<columnCount;i++) {
System.out.println(rs.getString(i+1)+"\t");
}
System.out.println("\n");
}
}
}else{
System.out.println("该Sql语句影响的记录有"+stmt.getUpdateCount()+"条");
}
}
}
public static void main(String[] args) throws Exception{
ExecuteSQL es = new ExecuteSQL();
es.initParam("D:\\study\\IdeaProject\\src\\jdbc\\mysql.ini");
System.out.println("----------执行查询数据的查询语句");
es.executeSql("select *"+" from people");
}
}
mysql.ini文件如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
usr=root
pass=root