java程序 *** 作MySQL数据库

java程序 *** 作MySQL数据库,第1张

数据库内容

  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/20030

下面是一个从 mysql 数据库获取用户信息的例子,可以参考一下:

import java.sql.Connection

import java.sql.DriverManager

import java.sql.ResultSet

import java.sql.SQLException

import java.sql.Statement

import java.util.ArrayList

import java.util.List

// 用户类,存储单个用户信息

class User {

private int id

private String name

public User(int id, String name) {

this.id = id

this.name = name

}

public int getId() {

return id

}

public void setId(int id) {

this.id = id

}

public String getName() {

return name

}

public void setName(String name) {

this.name = name

}

@Override

public String toString() {

return "User [id=" + id + ", name=" + name + "]"

}

}

public class Demo1 {

public static void main(String[] args) throws ClassNotFoundException, SQLException {

// 本例使用 mysql 数据库,演示将数据库 test 的 tb_users 表中的用户信息

// 放到 List 中

// 加载数据驱动

Class.forName("com.mysql.jdbc.Driver")

// 数据库连接字符串, 此例数据库为 test

String url = "jdbc:mysql://localhost:3306/test"

String user = "root" // 数据库用户名

String password = "" // 数据库密码

// 打开一个数据连接

Connection conn = DriverManager.getConnection(url, user, password)

Statement stmt = conn.createStatement()

// 获取表 tb_users 所有用户信息到结果集中

ResultSet rs = stmt.executeQuery("SELECT id, name FROM tb_users")

// 定义一个存放用户信息的 List

List<User> users = new ArrayList<>()

// 提取用户信息,并将用户信息放入 List

while (rs.next()) {

// 获取用户ID

int id = rs.getInt(1)

// 获取用户名

String name = rs.getString(2)

users.add(new User(id, name))

}

rs.close()

stmt.close()

conn.close()

// 显示用户信息

for (User u : users) {

System.out.println(u)

}

}

}

Java要连接数据库,那么首先你必须安装mysql数据库。

安装好mysql之后,安装JDK了。

安装好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()

} } }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6797017.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-28
下一篇 2023-03-28

发表评论

登录后才能评论

评论列表(0条)

保存