java操作gaussDB数据库

package com.shiwusuo.ReadHdfsToClickHouse.gauss

import java.sql.{Connection, DriverManager}
import java.util.Properties

import org.apache.spark.sql.DataFrame

import scala.collection.mutable.ArrayBuffer;

object GaussDBUtils {

  val urls = application.gaussURL //数据库URL
  val username = application.gaussName //用户名
  val password = application.gaussPass //密码
  val database = application.gaussDatabase
  val gaussCreateDatabase = application.gaussCreateDatabase
  //val driver = "org.postgresql.Driver"
  val driver = application.driver
  var conn: Connection = null;

  def getConnection(): Connection = {
    try {
      Class.forName(driver)
      conn = DriverManager.getConnection(urls, username, password)
      conn
    } catch {
      case e: Throwable => e.printStackTrace()
        println("连接gaussDB失败===请检查原因")
        conn
    }
  }

  //创建表
  def createGaussTable(sql: String): Unit = {
    try {
      val connection = getConnection()
      val statement = connection.createStatement()
      statement.executeUpdate(sql)
      statement.close()
    } catch {
      case e: Exception =>
        e.printStackTrace()
    }

  }

  //判断是否存在该表
  def tableExists(database: String, tablName: String): Boolean = {
    val connection = getConnection()
    val set = connection.getMetaData.getTables(null, database, tablName, null)
    if (set.next()) {
      return true
    } else {
      println("gaussDB中" + tablName + "不存在")
      return false
    }
  }

  //创建数据库
  def createDatabase(): Unit = {
    val connection = getConnection()
    val statement = connection.createStatement()
    statement.executeUpdate(gaussCreateDatabase)
    statement.close()
  }

  //查询 、执行sql语句
  def ReadFromGaussDB(sql: String): Unit = {
    try {
      val connection = getConnection()
      val statement = connection.createStatement()
      val set = statement.executeQuery(sql)
      while (set.next()) {
        val str = set.getString(2)
        println(str)
      }
    }catch {
      case e: Exception =>
        e.printStackTrace()
    }
  }

  //获取gaussDB中所有表名
  def getTablesByGaussDB(db: String) :ArrayBuffer[String]={
    val tablesList = new ArrayBuffer[String]()
    val connection = getConnection()
    val set = connection.getMetaData.getTables(null,db,null,null)
    while (set.next()) {
      val str: String = set.getString("TABLE_NAME")
      tablesList += str
      // println(str)
    }
    tablesList
  }

  //根据resourceId删除gaussDB数据
  def deleteDataByResourceId(sql:String): Unit ={
      val connection = getConnection()
      val statement = connection.createStatement()
      statement.executeUpdate(sql)
  }



  //插入gaussDB库中
  def insertgaussDBTable(table: String, df: DataFrame): Unit = {
    val connectionProperties = new Properties()
    connectionProperties.setProperty("user", username)
    connectionProperties.setProperty("password", password)
    println("+++++++开始写入GaussDB++++++" + table + "共有" + df.count())
    df.write.mode("append").option("batchsize", "50000").option("isolationLevel", "NONE").
      option("numPartitions", "1").jdbc(urls, table, connectionProperties)
    println("=================GaussDB完成写入========" + table + "====================")
  }


  def main(args: Array[String]): Unit = {
    //val bool = tableExists("gaussdb","test_01087")
    //println(bool)
    //val a = "CREATE TABLE gaussdb.CDPCP\n       (\n         code bigint NULL,\n        ident bigint NULL,\n        len bigint NULL,\n        lineNum1 bigint NULL,\n        lineNum2 bigint NULL,\n        lineNum3 bigint NULL,\n        lineNum4 bigint NULL,\n        lineName varchar(10000000) NULL,\n        begTime bigint NULL,\n        endTime bigint NULL,\n        comDur bigint NULL,\n        meanID varchar(10000000) NULL,\n        siteID varchar(10000000) NULL,\n        unitID varchar(10000000) NULL,\n        taskID varchar(10000000) NULL,\n        guid bigint NULL,\n        storTime bigint NULL,\n        mdSecDeg varchar(10000000) NULL,\n        fileSecDeg varchar(10000000) NULL,\n        secDegPro varchar(10000000) NULL,\n        ipVer bigint NULL,\n        srcAddr varchar(10000000) NULL,\n        dstAddr varchar(10000000) NULL,\n        srcPort bigint NULL,\n        dstPort bigint NULL,\n        protNum bigint NULL,\n        srcAddrV6 varchar(10000000) NULL,\n        dstAddrV6 varchar(10000000) NULL,\n        srcLoc varchar(10000000) NULL,\n        dstLoc varchar(10000000) NULL,\n        srcISP varchar(10000000) NULL,\n        dstISP varchar(10000000) NULL,\n        srcAS varchar(10000000) NULL,\n        dstAS varchar(10000000) NULL,\n        protInfo varchar(10000000) NULL,\n        linkInfo varchar(10000000) NULL,\n        protType varchar(10000000) NULL,\n        protName varchar(10000000) NULL,\n        mulRouFlag bigint NULL,\n        intFlag bigint NULL,\n        strDirec bigint NULL,\n        pktNum bigint NULL,\n        payLen bigint NULL,\n        hashId bigint NULL,\n        sessionID varchar(10000000) NULL,\n        resourceId varchar(10000000) NULL\n       )"
    //createGaussTable(a)
    //createtable
   // ReadFromGaussDB("select * from test_0110.user")
    //val strings = getTablesByGaussDB("test_0301")
    //strings.foreach(println)
    //DELETE FROM test_0110.AOE WHERE resourceId = 518824231216091205
    val b ="DELETE FROM test_0110.\"ANS\" WHERE \"resourceId\" = '518824231216091205'"
    println(b)
    deleteDataByResourceId(b)
  }

}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot连接GaussDB数据库需要以下步骤: 1. 添加GaussDB JDBC驱动依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.huawei.gaussdb.jdbc</groupId> <artifactId>gaussdb-jdbc</artifactId> <version>1.1.0</version> </dependency> ``` 2. 配置数据源 在application.properties或application.yml文件中配置数据源信息,例如: ```yaml spring.datasource.url=jdbc:gaussdb://localhost:25308/mydb spring.datasource.username=myusername spring.datasource.password=mypassword spring.datasource.driver-class-name=com.huawei.gaussdb.jdbc.Driver ``` 其中,spring.datasource.url指定GaussDB数据库的连接参数,包括主机名、端口号和数据库名称;spring.datasource.username和spring.datasource.password分别指定连接数据库的用户名和密码;spring.datasource.driver-class-name指定GaussDB JDBC驱动程序的类名。 3. 编写数据访问代码 可以使用Spring Data JPA或MyBatis等ORM框架进行数据访问,例如: 使用Spring Data JPA: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 使用MyBatis: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(Long id); } ``` 4. 使用数据访问接口 在需要使用数据访问的地方,例如Controller、Service或其他组件中,注入数据访问接口,例如: ```java @RestController public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElse(null); } } ``` ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUser(Long id) { return userMapper.findById(id); } } ``` 以上是使用Spring Boot连接GaussDB数据库的基本步骤,具体实现方式可以根据项目需求和开发经验进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值