日期:2014-05-16 浏览次数:20609 次
导入包mysql-connector-java-5.0.5-bin.jar

[java code]
/*
*@author: ZhengHaibo
*web: blog.csdn.net/nuptboyzhb
*mail: zhb931706659@126.com
*2012-10-6 Nanjing njupt
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class helloworld {
private Connection conn = null;
PreparedStatement statement = null;
// connect to MySQL
void connSQL() {
String urle = "jdbc:mysql://localhost:3306/testdb";//port:3306 database:testdb
String username = "root";//user
String password = "931706659";//password
try {
Class.forName("com.mysql.jdbc.Driver" );//加载驱动,连接数据库
conn = DriverManager.getConnection(urle,username, password );
}
//捕获加载驱动程序异常
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"装载 JDBC/ODBC 驱动程序失败。" );
cnfex.printStackTrace();
}
//捕获连接数据库异常
catch ( SQLException sqlex ) {
System.err.println( "无法连接数据库" );
sqlex.printStackTrace();
}
}
// disconnect to MySQL
void deconnSQL() {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
System.out.println("关闭数据库问题 :");
e.printStackTrace();
}
}
// execute selection language
ResultSet selectSQL(String sql) {
ResultSet rs = null;
try {
statement = conn.prepareStatement(sql);
rs = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// execute insertion language
boolean insertSQL(String sql) {
try {
statement = conn.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println("插入数据库时出错:");
e.printStackTrace();
} catch (Exception e) {
System.out.println("插入时出错:");
e.printStackTrace();
}
return false;
}
//execute delete language
boolean deleteSQL(String sql) {
try {
statement = conn.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println("插入数据库时出错:");
e.printStackTrace();
} catch (Exception e) {
System.out.println("插入时出错:");
e.printStackTrace();
}
return false;
}
//execute update language
boolean updateSQL(String sql) {
try {
statement = conn.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println("插入数据库时出错:");
e.printStackTrace();
} catch (Exception e) {
System.out.println("插入时出错:");
e.printStackTrace();
}
return false;
}
// show data in ju_users
void layoutStyle2(ResultSet rs) {
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" id" + "\t\t" + "name" +"\t\t" + "age" + "\t\t" +"work"+ "\t\t" + "others");
System.out.println("-----------------");
try {
while (rs.next()) {
System.out.println(rs.getInt("_id") + "\t\t"
+ rs.getString("name") + "\t\t"
+rs.getInt("age") +