您的位置:首页 > 编程语言 > Java开发

在Myeclipse中用Java语言操作mysql数据库

2016-03-19 10:39 567 查看
package OperateMysql;

import java.sql.*;

public class MysqlTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
BaseDao basedao = new BaseDao();
Connection conn = basedao.getConnection();
basedao.add(conn);
basedao.delete(conn);
basedao.update(conn);
basedao.query(conn);
basedao.close();
}

}
class BaseDao {
private static String url = "jdbc:mysql://localhost:3306/mysqltest";
private static String user = "root";
private static String password = "123456";
private Connection conn;
private static Statement sm;
private static ResultSet rs;
private static String sql;

// 连接数据库函数
public Connection getConnection() {
try {
// 初始化驱动包
Class.forName("com.mysql.jdbc.Driver");
// 根据数据库连接字符,名称,密码给conn
System.out.println("开始尝试连接数据库!");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

// 查询函数
public void query(Connection conn) {
sql = "select * from EMP";
try {
sm = conn.createStatement();
rs = sm.executeQuery(sql);
while (rs.next()) {
System.out.println("ID: " + rs.getString(1) + "\tNAME: "
+ rs.getString(2) + "\tAGE: " + rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}

}

// 添加表数据
public void add(Connection conn) {
sql = "insert into EMP(ID,NAME,AGE)" + " values ('0004','lucyyyy','14')";
try {
sm = conn.createStatement();
sm.executeUpdate(sql);
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}
}

// 删除数据
public void delete(Connection conn) {
sql = "delete from EMP " + "where ID='6'";
try {
sm = conn.createStatement();
sm.executeUpdate(sql);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
}
}

// 修改数据
public void update(Connection conn) {
sql = "update EMP set AGE='12' where ID='2'";
try {
sm = conn.createStatement();
sm.executeUpdate(sql);
System.out.println("更新成功");
} catch (Exception e) {
e.printStackTrace();
}
}

public void close() {// 6.释放资源
try { // 捕捉异常
try {
if (rs != null) { // 当ResultSet对象的实例rs不为空时
rs.close(); // 关闭ResultSet对象
}
} finally {
try {
if (sm != null) { // 当Statement对象的实例sm不为空时
sm.close(); // 关闭Statement对象
}
} finally {
if (conn != null) { // 当Connection对象的实例conn不为空时
conn.close(); // 关闭Connection对象
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err); // 输出异常信息
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: