DEV Community

wei chang
wei chang

Posted on

Using a database in the Cangjie development language

Today, I tried out CodeGenie, which I saw at the developer conference. It was really great. AI is influencing all walks of life. These days, You LAN Jun has a deep understanding of this. As an employee, one must maintain a state of continuous learning; otherwise, there is a possibility of being replaced.
Today, I’d like to share with you all how to use a database in the Cangjie development language.
Here we are talking about relational databases. First, we still need to introduce the corresponding module. The module of a relational database in the Cangjie language is:

import ohos.relational_store.*  
Enter fullscreen mode Exit fullscreen mode

The operation process of the database that follows might be quite familiar to many friends. It is in sequence: obtaining the database, creating tables, and then performing operations such as adding, deleting, modifying, and querying. This is the sequence of steps in any development language. However, the writing method of Cangjie might be somewhat different.
The method by which Cangjie acquires data is:

getRdbStore(context, config)  
Enter fullscreen mode Exit fullscreen mode

Its two parameters are the application context and the configuration information of the database respectively. The main problem is that it is rather troublesome to write the application context. First, in the main_ability.cj file, define the global context parameters and assign values:

var globalAbilityContext: Option<AbilityContext> = Option<AbilityContext>.None

globalAbilityContext = Option<AbilityContext>.Some(this.context)  
Enter fullscreen mode Exit fullscreen mode

The positions of these two lines of code are as follows:

Image description

Now back to the database page. Here, another method is written:

func getContext(): AbilityContext {
     match(globalAbilityContext) {
         case Some(context) => context
         case _ => throw Exception("can not get globalAbilityContext.")
     }
 }  
Enter fullscreen mode Exit fullscreen mode

The database can be obtained now:

var rdbStore: RdbStore = getRdbStore(getStageContext(getContext()), StoreConfig("RdbTest.db", SecurityLevel.S1)) 
Enter fullscreen mode Exit fullscreen mode

After obtaining the database, we can try to create a table. We have been writing the mall application, so I will create a product table. The fields will only write the id, product and price:

rdbStore.executeSql("CREATE TABLE IF NOT EXISTS GOODSLIST(ID int NOT NULL, NAME varchar(255) NOT NULL, PRICE int,  PRIMARY KEY (Id))")   
Enter fullscreen mode Exit fullscreen mode

Now try to insert data into the table:

var values = HashMap<String, ValueType>()
values.put("ID", ValueType.integer(1))
values.put("NAME", ValueType.string("T恤"))
values.put("PRICE", ValueType.integer(79))

rdbStore.insert("GOODSLIST", values) 
Enter fullscreen mode Exit fullscreen mode

To verify the successful insertion, the query operation is carried out next:

let resultSet = rdbStore.querySql("SELECT * FROM GOODSLIST") 
Enter fullscreen mode Exit fullscreen mode

The writing method of the query is relatively simple. resultSet is the result set obtained from the query. Now, I will demonstrate to you how to extract data from this result set:

if(resultSet.goToNextRow()){
  let id = resultSet.getLong(resultSet.getColumnIndex("ID"));
  let name = resultSet.getString(resultSet.getColumnIndex("NAME"));
  let price = resultSet.getLong(resultSet.getColumnIndex("PRICE"));
  AppLog.info('id:' + id.toString()  + ',商品:' + name.toString() + ',价格:' +  price.toString())
}   
Enter fullscreen mode Exit fullscreen mode

“goToNextRow” means pointing to the next line of the result set. It returns a bool value, and a return of true indicates that there is a value. If you want to print all the obtained data, you can use while:

while (resultSet.goToNextRow()) {
  let id = resultSet.getLong(resultSet.getColumnIndex("ID"));
  let name = resultSet.getString(resultSet.getColumnIndex("NAME"));
  let price = resultSet.getLong(resultSet.getColumnIndex("PRICE"));
  AppLog.info('id:' + id.toString()  + '  ,商品:' + name.toString() + '  ,价格:' +  price.toString())
}    
Enter fullscreen mode Exit fullscreen mode

Take a look at the execution result:

Image description

So far, we have basically covered the database of Cangjie. Because both modification and deletion can be operated by creating data. For example, to delete a piece of data:

rdbStore.executeSql("DELETE FROM GOODSLIST WHERE ID = ?", [ValueType.integer(3)]) 
Enter fullscreen mode Exit fullscreen mode

In summary, if the operation has a return value, such as a query, the querySql method can be used. For operations without a return value, the executeSql method can be used.
That’s all for today’s content. Thank you for reading.

Top comments (0)