数据库内容
java源代码 (代码实现的是查询成绩为 的人员信息 至于其他功能的 代码中有注释) 注意 在eclipse里运行程序的时候 要工程里插入jar包 否则运行异常! import java sql *import java io *class database_manage { public Connection conn = null public ResultSet rs = null private String DatabaseDriver = " mysql jdbc Driver" // DataSource 数据源名称DSN private String DatabaseConnStr = "jdbc:mysql://localhost: /people_manage?useUnicode=true&characterEncoding=utf " + " root root" public void setDatabaseDriver(String Driver) { this DatabaseDriver = Driver } public String getDatabaseDriver() { return (this DatabaseDriver) } public void setDatabaseConnStr(String ConnStr) { this DatabaseConnStr = ConnStr } public String getDatabaseConnStr() { 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())// 输出到客户端 } } public ResultSet query(String sql) {// 查询数据库 rs = nulltry { conn = DriverManager getConnection( "jdbc:mysql://localhost: /people_manage?useUnicode=true&characterEncoding=utf " "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 = try { conn = DriverManager getConnection( "jdbc:mysql://localhost: /people_manage?useUnicode=true&characterEncoding=utf " "root" "root") Statement stmt = conn createStatement() num = stmt executeUpdate(sql)} catch (SQLException ex) { System err println("执行插入有错误:" + ex getMessage()) System out print("执行插入有错误:" + ex getMessage())// 输出到客户端 } CloseDataBase()return num } public void CloseDataBase() {// 关闭数据库 try { conn close()} catch (Exception end) { System err println("执行关闭Connection对象有错误 " + end getMessage()) System out print("执行执行关闭Connection对象有错误 有错误:" + end getMessage())// 输出到客户端 } } } class people { private String uid private String name private String banji private int score public people() { } public people(String uid String name String banji) { this uid = uidthis name = namethis banji = banji } public people(String uid String name String banji int score) { this uid = uidthis name = namethis banji = banjithis score = score } public String getUid() { return uid } public void setUid(String uid) { this uid = uid } public String getName() { return name } public void setName(String name) { this name = name } public String getBanji() { return banji } public void setBanji(String banji) { this banji = banji } public int getScore() { return score } public void setScore(int score) { this score = score } } public class manage { private people[] people_array // 对象数组 public void add_people(String uid String name) { String sql = "insert people (uid name) values ( " + uid + " " + name + " )"// sql插入语句 // String sql = "insert people (uid name) values ( uid tom )" database_manage db_obj = new database_manage()db_obj update_database(sql) } public void update_people(String uid String name) { String sql = "update people set name= " + name + " where uid= " + uid + " "database_manage db_obj = new database_manage()db_obj update_database(sql) } public void delete_people(String uid) { String sql = "delete from people where uid= " + uid + " " database_manage db_obj = new database_manage() db_obj update_database(sql) } public people query_people(String uid) { database_manage db_obj = new database_manage()// String adminid=nullString uid_new name banjiuid_new = nullname = nullbanji = nullString sql_query = "select * from people where uid= " + uid + " " try { ResultSet rs = db_obj query(sql_query) if (rs next()) { uid_new = rs getString("uid")name = rs getString("name")banji = rs getString("banji") } } catch (Exception e) { e getMessage()} people new_people = new people(uid_new name banji)return new_people } public people[] query_people_byscore(int score) { database_manage db_obj = new database_manage()String uid_new name banjiuid_new = nullname = nullbanji = nullint score_new =String sql_query = "select * from people where score=" + score// sql查询语句
try {
ResultSet rs = db_obj query(sql_query)// 查询后 返回结果集
int num =
ResultSet rs_new = rs
while (rs_new next()) {// 统计结果集中学生个数
num++
}
// System out println(num)
people_array = new people[num]
int i =
rs beforeFirst()// 返回结果集的开始
while (rs next()) {
uid_new = rs getString("uid")
name = rs getString("name")
banji = rs getString("banji")
score_new = rs getInt("score")
people_array [i] = new people(uid_new name banji score_new)
i++
}
} catch (Exception e) {
e getMessage()
}
return people_array
}
public static void main(String args[]) {
/*
* people new_people=new people()
*
* manage mr=new manage()//mr add_people(" " "小明")插入一个学生的信息
*
* new_people=mr query_people(" ")//查询uid= 的学生信息 返回对象 System out
* println(""+new_people getName()+" "+new_people getBanji())
* mr update_people(" " "小王")更新一个学生的信息
*
* new_people=mr query_people(" ")//更新后查询
*
* System out println(""+new_people getName()+" "+new_people getBanji(
* ))
*/
manage mr = new manage()
// mr delete_people(" ")删除uid= 的学生信息
people[] people_array// 声明对象数组
people_array = mr query_people_byscore( )// 返回成绩为一百的学生类数组 后输出
int num =
num = people_array length
for (int i = i <numi++) {
System out println(people_array[i] getUid() + " "
+ people_array[i] getName() + " "
+ people_array[i] getBanji() + " "
+ people_array[i] getScore())
}
}
}
lishixinzhi/Article/program/Java/JSP/201311/20030JDBC连接数据库
•创建一个以JDBC连接数据库的程序,包含7个步骤:
1、加载JDBC驱动程序:
在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机),
这通过java.lang.Class类的静态方法forName(String className)实现。
例如:
try{
//加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver")
}catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!")
e.printStackTrace()
}
成功加载后,会将Driver类的实例注册到DriverManager类中。
2、提供JDBC连接的URL
•连接URL定义了连接数据库时的协议、子协议、数据源标识。
•书写形式:协议:子协议:数据源标识
协议:在JDBC中总是以jdbc开始
子协议:是桥连接的驱动程序或是数据库管理系统名称。
数据源标识:标记找到数据库来源的地址与连接端口。
例如:(MySql的连接URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk
useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为
gb2312或GBK,本参数必须设置为true 。characterEncoding=gbk:字符编码方式。
3、创建数据库的连接
•要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,
该对象就代表一个数据库的连接。
•使用DriverManager的getConnectin(String url , String username ,
String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和
密码来获得。
例如:
//连接MySql数据库,用户名和密码都是root
String url = "jdbc:mysql://localhost:3306/test"
String username = "root"
String password = "root"
try{
Connection con =
DriverManager.getConnection(url , username , password )
}catch(SQLException se){
System.out.println("数据库连接失败!")
se.printStackTrace()
}
4、创建一个Statement
•要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3
种类型:
1、执行静态SQL语句。通常通过Statement实例实现。
2、执行动态SQL语句。通常通过PreparedStatement实例实现。
3、执行数据库存储过程。通常通过CallableStatement实例实现。
具体的实现方式:
Statement stmt = con.createStatement()
PreparedStatement pstmt = con.prepareStatement(sql)
CallableStatement cstmt =
con.prepareCall("{CALL demoSp(? , ?)}")
方法/步骤Java要连接数据库,那么首先你必须安装mysql数据库,mysql在windows7下面是怎么安装的呢?这里暂时不做详细解析,后面的章节中会解释的
当你安装好mysql之后,那么你现在应该安装JDK了(JDK1.6就可以),
安装好JDK之后,就是安装Eclipse了,要支持JDK版本,Eclipse安装的时候会自动去找JDK安装位置的,如果你是解压版的Eclipse,就要配置eclipse.ini文件了,将对应的JDK配置好,这些已经准备就绪的时候,就到mysql中创建数据库和表
先创建数据库:
CREATE DATABASE SCUTCS
接着,创建表:
CREATE TABLE STUDENT
(
SNO CHAR(7) NOT NULL,
SNAME VARCHAR(8) NOT NULL,
SEX CHAR(2) NOT NULL,
BDATE DATE NOT NULL,
HEIGHT DEC(5,2) DEFAULT 000.00,
PRIMARY KEY(SNO)
)
然后插入数据,可以用SQL语句insert into <表名>values (value1, value2, ...)
下面,我们来编写.java文件来演示一下如何访问MySQL数据库。
import java.sql.*
public class JDBCTest {
public static void main(String[] args){
// 驱动程序名 String driver = "com.mysql.jdbc.Driver"
// URL指向要访问的数据库名scutcs String url = "jdbc:mysql://127.0.0.1:3306/scutcs"
// MySQL配置时的用户名 String user = "root" // MySQL配置时的密码 String password = "root"
try { // 加载驱动程序Class.forName(driver)
// 连续数据库Connection conn = DriverManager.getConnection(url, user, password)
if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!")
// statement用来执行SQL语句Statement statement = conn.createStatement()
// 要执行的SQL语句String sql = "select * from student"
// 结果集ResultSet rs = statement.executeQuery(sql)
while(rs.next()) // 选择sname这列数据 name = rs.getString("sname
// 输出结果 System.out.println(rs.getString("sno") + "\t" + name) }
rs.close() conn.close()
} catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!")e.printStackTrace()
} catch(SQLException e) {
e.printStackTrace()
} catch(Exception e) {
e.printStackTrace()
} } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)