日期:2014-05-16  浏览次数:20693 次

连接MySQL测试程序


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateDbandTable {
	public static void main(String[] args) {
		Connection con = null;
		Statement sm = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager
					.getConnection(
							"jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8",
							"root", "ppzhang");
			sm = con.createStatement();
			sm.addBatch("DROP DATABASE IF EXISTS sms;");
			sm.addBatch("CREATE DATABASE sms;");
			sm.addBatch("USE sms;");
			sm.addBatch("DROP TABLE IF EXISTS test_table;");
			StringBuffer sb = new StringBuffer();
			sb.append("CREATE TABLE test_table(");
			sb.append(" id int(6)unsigned NOT NULL auto_increment,");
			sb.append(" name0 varchar(10) default NULL,");
			sb.append(" name1 varchar(10) character set latin1 default NULL,");
			sb.append(" name2 varchar(10) character set gb2312 default NULL,");
			sb.append(" name3 varchar(10) character set gbk default NULL,");
			sb.append("PRIMARY KEY (id)");
			sb.append(")ENGINE=InnoDB DEFAULT CHARSET=utf8;");
			sm.addBatch(sb.toString());
			sm.executeBatch();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (sm != null) {
				try {
					sm.close();

				} catch (SQLException e) {
					sm = null;
				}
				if (con != null) {
					try {
						con.close();
					} catch (SQLException e) {
					}
					con = null;
				}
			}
		}
	}
}



附上连接所需要的mysql的connector包。