java程序操作MySQL数据库
2012-12-08 15:43:06 来源:WEB开发网核心提示: 数据库内容: java源代码:(代码实现的是查询成绩为100的人员信息,至于其他功能的代码中有注释)注意:在eclipse里运行程序的时候,java程序操作MySQL数据库,要工程里插入jar包,否则运行异常!import java.sql.*;import java.io.*;class database_mana
数据库内容:
java源代码:(代码实现的是查询成绩为100的人员信息,至于其他功能的
代码中有注释)
注意:在eclipse里运行程序的时候,要工程里插入jar包,否则运行异常!
import java.sql.*;
import java.io.*;
import java.io.*;
class database_manage {
public Connection conn = null;
public ResultSet rs = null;
private String DatabaseDriver = "com.mysql.jdbc.Driver";
// DataSource 数据源名称DSN
private String DatabaseConnStr = "jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8"
+ ",root,root";
// DataSource 数据源名称DSN
private String DatabaseConnStr = "jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8"
+ ",root,root";
public void setDatabaseDriver(String Driver) {
this.DatabaseDriver = Driver;
}
this.DatabaseDriver = Driver;
}
public String getDatabaseDriver() {
return (this.DatabaseDriver);
}
return (this.DatabaseDriver);
}
public void setDatabaseConnStr(String ConnStr) {
this.DatabaseConnStr = ConnStr;
}
this.DatabaseConnStr = ConnStr;
}
public String getDatabaseConnStr() {
return (this.DatabaseConnStr);
}
return (this.DatabaseConnStr);
}
public database_manage() {// 构造函数连接数据库
try {
Class.forName(DatabaseDriver);
} catch (java.lang.ClassNotFoundException e) {
System.err.println("加载驱动器有错误:" + e.getMessage());
System.out.print("执行插入有错误:" + e.getMessage());// 输出到客户端
}
}
try {
Class.forName(DatabaseDriver);
} catch (java.lang.ClassNotFoundException e) {
System.err.println("加载驱动器有错误:" + e.getMessage());
System.out.print("执行插入有错误:" + e.getMessage());// 输出到客户端
}
}
public ResultSet query(String sql) {// 查询数据库
rs = null;
try {
conn = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8",
"root", "root");
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
System.err.println("执行查询有错误:" + ex.getMessage());
System.out.print("执行查询有错误:" + ex.getMessage()); // 输出到客户端
}
return rs;
}
public int update_database(String sql) {// 更新或插入数据库
int num = 0;
try {
conn = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8",
"root", "root");
Statement stmt = conn.createStatement();
num = stmt.executeUpdate(sql);
} catch (SQLException ex) {
System.err.println("执行插入有错误:" + ex.getMessage());
System.out.print("执行插入有错误:" + ex.getMessage());// 输出到客户端
}
int num = 0;
try {
conn = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/people_manage?useUnicode=true&characterEncoding=utf8",
"root", "root");
Statement stmt = conn.createStatement();
num = stmt.executeUpdate(sql);
} catch (SQLException ex) {
System.err.println("执行插入有错误:" + ex.getMessage());
System.out.print("执行插入有错误:" + ex.getMessage());// 输出到客户端
}
更多精彩
赞助商链接