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

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 = "";
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() + "\tNAME: "
+ rs.getString() + "\tAGE: " + rs.getString());
}
} 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); // 输出异常信息
}
}
}
上一篇:我的Android进阶之旅------>Android【设置】-【语言和输入法】-【语言】列表中找到相应语言所对应的列表项


下一篇:Android默认输入法语言的修改以及SettingsProvider作用