1)准备
a》jdbc驱动包
2)原理:
编写jdbc数据库连接,命令行传递参数,最后打成jar包
3)实施
public static void main(String[] args) {
// 输入参数判断
// 1)DB_URL
// 2)Username
// 3)Password 4)Sql-执行Sql
if (args == null || args.length < 4) {
System.out.println("传递的参数不足4个【url,Username,Password,Sql(含空格用双引号引起)】,参数之间用空格分开。");
return;
}
// 获取参数
String url = args[0];
String user = args[1];
String password = args[2];
String sql = args[3];
// 设置驱动名称
String driverName = "oracle.jdbc.driver.OracleDriver";
if (url.contains("jdbc:mysql")) {
driverName = "com.mysql.jdbc.Driver";
}
// 加载驱动,建立连接
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName(driverName);
con = DriverManager.getConnection(url, user, password);
System.out.println("db连接成功.");
statement = con.createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData resultMetaData = resultSet.getMetaData();
// 获取所有列名
int cols = resultMetaData.getColumnCount();
String resultRow = "";
for (int i = 1; i <= cols; i++) {
resultRow += resultMetaData.getColumnName(i) + " ";
}
System.out.println("数据结果:");
System.out.println(resultRow);
// 获取所有值
while (resultSet.next()) {
resultRow = "";
for (int i = 1; i <= cols; i++) {
try {
resultRow += resultSet.getString(i) + " ";
} catch (NullPointerException e) {
e.printStackTrace();
}
}
System.out.println(resultRow);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
statement.close();
con.close();
System.out.println("db连接关闭成功.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}