我想更新数据库中的兴趣字段.我的SQL查询如下所示
更新Table_Name set Interest = Principal*Power((1 +(rate/100),year)
此查询在MySQL中正常工作但不适用于SQLite.
该错误表明找不到功率功能
有谁知道如何解决这个问题,因为我必须使用查询,因为我需要一次更新超过3000条记录.
rma*_*ddy 18
sqlite没有很多可用的功能.但好消息是,添加自己的东西很容易.
首先写一个电源功能:
void sqlite_power(sqlite3_context *context, int argc, sqlite3_value **argv) {
double num = sqlite3_value_double(argv[0]); // get the first arg to the function
double exp = sqlite3_value_double(argv[1]); // get the second arg
double res = pow(num, exp); // calculate the result
sqlite3_result_double(context, res); // save the result
}
Run Code Online (Sandbox Code Playgroud)
然后你需要注册功能:
int res = sqlite3_create_function(dbRef, "POWER", 2, SQLITE_UTF8, NULL, &sqlite_power, NULL, NULL);
Run Code Online (Sandbox Code Playgroud)
这2是函数的参数个数.dbRef当然是sqlite3 *数据库参考.
您还可以从 python创建一个 SQLite用户定义函数。基于 docs.python.org 上的示例:sqlite3.Connection.create_function
创建一个python函数:
def sqlite_power(x,n):
return int(x)**n
print(sqlite_power(2,3))
# 8
Run Code Online (Sandbox Code Playgroud)
基于python函数创建一个SQLite用户自定义函数:
con = sqlite3.connect(":memory:")
con.create_function("power", 2, sqlite_power)
Run Code Online (Sandbox Code Playgroud)
用它:
cur = con.cursor()
cur.execute("select power(?,?)", (2,3))
print cur.fetchone()[0]
# 8
Run Code Online (Sandbox Code Playgroud)
我也在为此苦苦挣扎,但是如果您只需要 2 的幂(或倍数等),则有一种更简单的方法:
使用移位运算符,例如
SELECT 1 << mytable.value
SELECT 1 << (table.x + etc..)
Run Code Online (Sandbox Code Playgroud)