JDBC-druid-DAO对mysql数据库操作

连接数据库需要导入的包(API接口)

链接:https://pan.baidu.com/s/1rAmg4HJcboCwskFwWgwpMg?pwd=h93b
提取码:h93b

连接数据库的四种方式

自主创建Driver对象

示例:
public static void main(String[] args) throws SQLException {
//    //先创建驱动对象driver
//    Driver driver = new Driver();
//    //2,得到链接数据库的URL
//    String URL="jdbc:mysql://localhost:3306/c_02";
//    //将用户名和密码放入到Properties中
//    Properties properties = new Properties();
//    properties.setProperty("user","root");
//    properties.setProperty("password","cwj");
//    //调用驱动对象driver的connect方法
//    Connection connect = driver.connect(URL, properties);
    Connection connect = dbConnect.getconnection();

    //使用工具类dbConnection连接数据库并执行sql语句
    //sql语句
//    String sql = "select * from emp";
            String sql = "insert into emp values (0,'刘某','player',0,'1979-11-11',2000.0,null ,'10')";
    //使用createStatement执行sql语句
    Statement statement = connect.createStatement();
//    ResultSet resultSet = statement.executeQuery(sql);
//    if(resultSet!=null){
//      System.out.println("链接数据库成功并执行查询整表emp");
//
//    }
    //关闭资源流
    int i = statement.executeUpdate(sql);
    System.out.println(i>0?"成功?":"失败?");
    dbConnect.close(statement,connect);
//    statement.close();
//connect.close();

  }

加载properties文件连接数据库

示例

image-20231003131637822


public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
  //通过配置文件来连接数据库
  Properties properties = new Properties();
  properties.load(new FileInputStream("src\\com\\tom\\mysql.properties"));
  String user = properties.getProperty("user");
  String password = properties.getProperty("password");
  String driver = properties.getProperty("driver");
  String url = properties.getProperty("url");
  Class.forName(driver);
  Connection connection = DriverManager.getConnection(url, user, password);
  System.out.println(connection);

}

使用druid连接数据库

注意://德鲁伊相当于将Properties加载user或password封装到自己的方法中。

Properties properties = new Properties();
properties.load(new FileInputStream(“src\com\tom\mysql.properties”));

只需加载配置文件即可;

image-20231003131637822


user-这里是默认的root;

passwor-自己数据库的密码;

driver驱动-如果是mysql保持一致即可;

url-这里是链接本地mysql的c_02(数据库)-如果是使用mysql端口号为3306,即只需更改数据库的名字即可;

示例:
使用druid连接数据库并执行对应的sql语句

//德鲁伊有特有的连接方式-数据库连接池技术-可以限流和规范
//DruidDataSourceFactory
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

public class testDruid {
  public static void main(String[] args) {
      //德鲁伊相当于将Properties加载user或password封装到自己的方法中
    try {
      Properties properties = new Properties();
      properties.load(new FileInputStream("src\\com\\tom\\mysql.properties"));
      //德鲁伊有特有的连接方式-数据库连接池技术-可以限流和规范
      //DruidDataSourceFactory
      DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
      Connection connection = dataSource.getConnection();
      if(connection!=null){
        System.out.println("连接数据库成功");
      }else {
        System.out.println("连接数据库失败");
      }
      //执行sql语句
      String sql = "insert into emp values (0,'刘某','player',0,'1979-11-11',2000.0,null ,'10')";
      Statement statement = connection.createStatement();
      int i = statement.executeUpdate(sql);
      System.out.println(i>0?"成功":"失败");
    } catch (Exception e) {
      e.printStackTrace();
    }

  }
}

使用druid配置Dao来对mysql数据库操作

1,需要使用到刚才封装druidUtils-连接mysql数据

1,这里是将德鲁伊封装到druidUtils
public class druidUtils {
  //创建一个druid数据库连接池
  private static DataSource db;

  static {
    try {
      Properties properties = new Properties();
      properties.load(new FileInputStream("src\\com\\tom\\mysql.properties"));
      //德鲁伊有特有的连接方式-数据库连接池技术-可以限流和规范
      //DruidDataSourceFactory
      db = DruidDataSourceFactory.createDataSource(properties);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  //用数据库连接池db连接mysql数据库
  public static Connection getconnection() throws SQLException {
    return db.getConnection();
  }
  //释放资源
  public static void close( Statement statement,Connection connection){
    try {
      if(statement!=null){
        statement.close();
      }
      if(connection!=null){
        connection.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
2,创建BasicDao
public class BasicDao<T> {
  //这里需要用到泛型,泛型指具体的类型
  //Dao需要使用到druid工具类来连接数据库
  //Dao提供自己特有的查询选择器QueryRunner,来执行sql语句
  //1,创建QueryRunner查询选择器
  private QueryRunner queryRunner = new QueryRunner();
  //编写BasicDao的对mysql数据库操作的方法
  //1,sql(dml)语句
  public int update(String sql ,Object... Parameters){
    Connection connection = null;

    //注意:...代表sql语句中多个?即使用PreparedStatement(sql)
    try {
      connection=druidUtils.getconnection();
      return queryRunner.update(connection,sql,Parameters);
      //queryRunner.update(connection,sql,Parameters);等价于封装PreparedStatement(sql)方法
    } catch (SQLException e) {
      //注意:这里报错需要更改为运行时异常
      throw new RuntimeException(e);
    } finally {
      druidUtils.close(null,connection);
    }
  }
  //执行sql(query)查询语句(注意:泛型返回值-对应的dom映射)
  //1,查询多行多列,针对任意表
  public List<T> sqlQuery(String sql,Class<T> clazz,Object... Parameters){
    Connection connection = null;

    //注意:...代表sql语句中多个?即使用PreparedStatement(sql)
    try {
      connection=druidUtils.getconnection();
      //注意:new BeanListHandler<T>(clazz)->ResultSet->返回结果集
      return queryRunner.query(connection,sql,new BeanListHandler<T>(clazz),Parameters);
    } catch (SQLException e) {
      //注意:这里报错需要更改为运行时异常
      throw new RuntimeException(e);
    } finally {
      druidUtils.close(null,connection);
    }
  }
  //查询单行多列,针对任意表
  public T sqlQueryline(String sql,Class<T> clazz,Object... Parameters){
    Connection connection = null;

    //注意:...代表sql语句中多个?即使用PreparedStatement(sql)
    try {
      connection=druidUtils.getconnection();
      //注意:new BeanHandler<T>(clazz)->ResultSet->返回结果集
      return queryRunner.query(connection,sql,new BeanHandler<T>(clazz),Parameters);
    } catch (SQLException e) {
      //注意:这里报错需要更改为运行时异常
      throw new RuntimeException(e);
    } finally {
      druidUtils.close(null,connection);
    }
  }
  //查询单行单列,针对任意表
  public Object sqlQueryObj(String sql,Object... Parameters){
    Connection connection = null;

    //注意:...代表sql语句中多个?即使用PreparedStatement(sql)
    try {
      connection=druidUtils.getconnection();
      return queryRunner.query(connection,sql,new ScalarHandler(),Parameters);
    } catch (SQLException e) {
      //注意:这里报错需要更改为运行时异常
      throw new RuntimeException(e);
    } finally {
      druidUtils.close(null,connection);
    }
  }
}
3.创建JavaBean映射数据库中的表

image-20231003134035728


image-20231003134137882


4,UserDao
public class UserDao extends BasicDao<User>{
}
5,使用UserDao
public static void main(String[] args) {
  //创建UserDao对象
  UserDao userDao = new UserDao();
  //子类继承父类BasicDao可以调用父类的方法
  String sql = "select * from user where id = ?";
  List<User> users = userDao.sqlQuery(sql, User.class, 1);
  for (User user: users) {
    System.out.println(user);
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用Qt连接数据库可以使用Qt提供的Qt SQL模块,其中包含了Qt SQL模块的三个重要的类:QSqlDatabase、QSqlQuery和QSqlTableModel。 首先,我们需要添加Qt SQL模块到项目中。可以在.pro文件中添加"QT += sql"来使得项目能够使用Qt SQL模块。 接下来,我们需要创建一个QSqlDatabase对象来连接数据库。可以使用QSqlDatabase::addDatabase函数添加一个数据库连接,并设置相应的数据库驱动、主机名、用户名、密码等信息。例如,可以使用如下代码连接SQLite数据库: ``` QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("path_to_database_file.sqlite"); if (!db.open()) { qDebug() << "Unable to open database"; return; } ``` 在连接数据库成功后,我们可以执行SQL查询语句。可以使用QSqlQuery类来执行SQL语句,并获取结果。例如,可以使用如下代码执行一个查询语句并获取结果: ``` QSqlQuery query; query.exec("SELECT * FROM table_name"); while (query.next()) { QString column1 = query.value(0).toString(); int column2 = query.value(1).toInt(); // 处理查询结果 } ``` 除了手动执行SQL语句外,Qt还提供了QSqlTableModel类来简化数据库表的操作。通过设置数据库连接和表名,我们可以通过QSqlTableModel来从数据库中检索数据、更新数据等。例如,可以使用如下代码创建一个QSqlTableModel对象并从数据库中加载数据到表格视图中: ``` QSqlTableModel model; model.setTable("table_name"); model.setEditStrategy(QSqlTableModel::OnFieldChange); model.select(); QTableView tableView; tableView.setModel(&model); tableView.show(); QLineEdit filterLineEdit; QSortFilterProxyModel proxyModel; proxyModel.setSourceModel(&model); tableView.setModel(&proxyModel); connect(&filterLineEdit, &QLineEdit::textChanged, &proxyModel, &QSortFilterProxyModel::setFilterFixedString); ``` 以上就是使用Qt连接数据库的基本流程,通过Qt提供的Qt SQL模块和相关类可以方便地进行数据库操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值