2014-09-23 16:53:47

JDBCTest 命令行下自动load外部数据库驱动并执行SQL语句

保存为JDBCTest.java并编译:javac JDBCTest.java 执行:java JDBCTest com.mysql.jdbc.Driver jdbc:mysql://localhost/test root 123456 "select version()"

参数的顺序是驱动包、url、用户名、密码、sql语句。执行结果:

[[email protected]:~]$ java JDBCTest com.mysql.jdbc.Driver jdbc:mysql://localhost/test root 123456 "select version()"

version()[VARCHAR]

5.6.19

(JDBCTest.java会加载外部的驱动包,所以如果能出外网无需考虑是否存在对应的数据库驱动包)

JDBCTest.java源码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class JDBCTest {
	public static void main(String[] args) {
		try {
			try {
				Class.forName(args[0]);
			} catch (ClassNotFoundException e) {
				boolean classNotFound = true;
				BufferedReader br = new BufferedReader(new InputStreamReader(new URL("http://javaweb.org/jdbc/map.txt").openStream()));
				String str = "";
				while ((str = br.readLine()) != null) {
					String[] arr = str.split("=");
					if (arr.length == 2 && arr[0].trim().equals(args[0])) {
						try {
							URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
							Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
							m.setAccessible(true);
							m.invoke(ucl, new Object[] { new URL(arr[1]) });
							Class.forName(arr[0].trim());
							classNotFound = false;
							break;
						} catch (ClassNotFoundException ex) {
							throw ex;
						}
					}
				}
				if (classNotFound) {
					throw e;
				}
			}
			ResultSet rs = DriverManager.getConnection(args[1], args[2], args[3]).prepareStatement(args[4]).executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				System.out.print(rsmd.getColumnName(i) + "["+ rsmd.getColumnTypeName(i) + "]"+"\t");
			}
			System.out.println();
			while (rs.next()) {
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					if (i > 1) {
						System.out.print("\t");
					}
					System.out.print(rs.getObject(rsmd.getColumnName(i)));
				}
			}
			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

jar包版:

JDBCTest.jar 

执行:

[[email protected]:Downloads]$ java -jar JDBCTest.jar com.mysql.jdbc.Driver jdbc:mysql://localhost/test root 123456 "select version()"

version()[VARCHAR]

5.6.19

发表回复