发布网友 发布时间:2022-04-20 12:43
共1个回答
热心网友 时间:2022-04-09 00:24
myeclipse中使用JDBC连接MySQL连接数据库,可以新建一个java文件,使用JDBC操作数据库就可以,实例如下:import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBConnection {private final static String url = "jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=utf-8";//配置连接数据库的用户名和密码private final static String dbDriver = "com.mysql.jdbc.Driver";//mysql的驱动程序名private Connection con = null;// 通过构造方法加载数据库驱动static {try {Class.forName(dbDriver).newInstance();//利用反射实例化驱动类} catch (Exception ex) {System.out.println("数据库加载失败");}}// 创建数据库连接public boolean creatConnection() {try {con = DriverManager.getConnection(url);con.setAutoCommit(true);//提交sql语句} catch (SQLException e) {System.out.println(e.getMessage());System.out.println("creatConnectionError!");}return true;}// 对数据库的增加、修改和删除的操作public boolean executeUpdate(String sql) {if (con == null) {creatConnection();}try {Statement stmt = con.createStatement();//得到一个结果集,拿来遍历int iCount = stmt.executeUpdate(sql);return true;} catch (SQLException e) {System.out.println(e.getMessage());return false;}}// 对数据库的查询操作public ResultSet executeQuery(String sql) {ResultSet rs;try {if (con == null) {creatConnection();}Statement stmt = con.createStatement();//得到一个结果集,拿来查询try {rs = stmt.executeQuery(sql);} catch (SQLException e) {System.out.println(e.getMessage());return null;}} catch (SQLException e) {return null;}return rs;}}