GVKun编程网logo

我无法让Python的executemany使sqlite3正常工作

18

在这篇文章中,我们将为您详细介绍我无法让Python的executemany使sqlite3正常工作的内容。此外,我们还会涉及一些关于Cursorfastexecutemanyerror:('HY00

在这篇文章中,我们将为您详细介绍我无法让Python的executemany使sqlite3正常工作的内容。此外,我们还会涉及一些关于Cursor fastexecutemany error: ('HY000', '[HY000] [Microsoft][SQL Server Native Client 11.0]Unicode 转换失败 (0) (SQLExecute)')、For循环或executemany-Python和SQLite3、JDBC 中的execute()、executeQuery() 和executeUpdate() 方法有什么区别?、Making SQLITE/SQLITE3 executable scripts的知识,以帮助您更全面地了解这个主题。

本文目录一览:

我无法让Python的executemany使sqlite3正常工作

我无法让Python的executemany使sqlite3正常工作

我试图使用executemany将值插入数据库中,但对我来说不起作用。这是一个示例:

clist = []clist.append("abc")clist.append("def")clist.append("ghi")cursor.executemany("INSERT INTO myTable(data) values (?) ", clist)

这给了我以下错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The currentstatement uses 1, and there are 3 supplied.

但是,当我更改列表时,它可以正常工作:

clist = ["a", "b"]cursor.executemany("INSERT INTO myTable(data) values (?) ", clist)

它按预期工作!我可以在数据库中看到数据。为什么第一个列表不起作用而第二个列表却不起作用?

(PS:这只是一个示例,而不是实际的代码。为简单起见,我制作了一个小测试用例)。

答案1

小编典典

根据我对执行力的了解,您的意思是,

clist = [("abc", ), ("def", ), ("ghi", )]cursor.executemany("INSERT INTO myTable(data) values(?)", clist)

或类似的东西。不要在sqlite的语法上引用我,我已经有一段时间没有在应用程序中使用它了,但是您需要一个可迭代的元组(更常见的是可迭代的)。

您似乎收到的错误是它试图遍历您提供的每个字符串,因此您的语句的工作方式如下:

clist = [(''a'', ''b'', ''c''), (''d'', ''e'', ''f''), (''g'', ''h'', ''i'')]

我不知道您的第二个查询要完成什么,但它似乎是在解决另一个表,因此我猜不到模式信息,但是如果将单个字符串更改为多字符字符串,它也会失败。

Cursor fastexecutemany error: ('HY000', '[HY000] [Microsoft][SQL Server Native Client 11.0]Unicode 转换失败 (0) (SQLExecute)')

Cursor fastexecutemany error: ('HY000', '[HY000] [Microsoft][SQL Server Native Client 11.0]Unicode 转换失败 (0) (SQLExecute)')

如何解决Cursor fastexecutemany error: (''HY000'', ''[HY000] [Microsoft][SQL Server Native Client 11.0]Unicode 转换失败 (0) (SQLExecute)'')?

我正在尝试使用游标 fast_executemany 将几个大型 csv 文件上传到 sql server 数据库。下面是代码示例。

  if item.endswith(zip_ext):
      file_name = os.path.abspath(item)
      zip_ref = zipfile.ZipFile(file_name)
      zip_ref.extractall(directory)
      zip_ref.close()
      os.remove(file_name)

for item in os.listdir(directory): # Load and Edit CSV
   if item.endswith(ext):
       df = pd.read_csv(item)
       df.rename(columns={df.columns[0]:''InvoiceNo'',df.columns[2]:''OrderNo'',df.columns[20]:''Syscode'',df.columns[27]:''SpotDate'',df.columns[28]:''Network'',df.columns[30]:''Spottime'',df.columns[29]:''SpotLength'',df.columns[31]:''Program'',df.columns[32]:''SpotName'',df.columns[21]:''Source''},inplace=True)
      
       df[''BillDate'']=''2021-03-01'' # Enter Preferred Bill Date Here!
       df[''FileName'']=str(item)
       df[[''SpotDate'',''BillDate'',''Spottime'']]=df[[''SpotDate'',''Spottime'']].apply(pd.to_datetime)
       df[''Spottime'']=df[''Spottime''].dt.time
       df[''OrderNo'']=df[''OrderNo''].apply(lambda x: '''' if x == ''NULL'' else x)
       df = df[[''InvoiceNo'',''OrderNo'',''Syscode'',''SpotDate'',''Network'',''Spottime'',''SpotLength'',''Program'',''SpotName'',''Source'',''FileName'']]
       
# Connect to sql Server
       conn = pyodbc.connect(''DRIVER=sql Server Native Client 11.0;''
                             ''SERVER=PWDBS006sql;'' #UPDATED 2/4/21
                             ''DATABASE=Marketing Cross-Channel Affidavits;''
                             ''Trusted_Connection=yes;'',autocommit=True)
       crsr = conn.cursor()
       crsr.fast_executemany = False
       
# Insert Df to sql
       sql_statement = ''''''INSERT INTO dbo.SpectrumReach_Marketing (InvoiceNo,OrderNo,BillDate,Syscode,SpotDate,Network,Spottime,SpotLength,Program,SpotName,Source,FileName)
                        VALUES (?,?,?)''''''
       list_of_tuples = list(df.itertuples(index=False))
       crsr.executemany(sql_statement,list_of_tuples)
       
       crsr.close()
       conn.close() 

运行此代码时,我收到错误消息:(''HY000'',''[HY000] [Microsoft][sql Server Native Client 11.0]Unicode 转换失败 (0) (sqlExecute)''。

我已经将此代码用于来自几个来源的几个大型数据集,它们的格式应该完全相同,并且它有效,但对于特定供应商,它会中断并显示上述错误。此外,当我有 fast_executemany = False 时,此代码会运行,但由于我尝试传输的文件的大小,让数据上传这么慢是不可行的。

任何帮助将不胜感激!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

For循环或executemany-Python和SQLite3

For循环或executemany-Python和SQLite3

我最近开始学习Python和SQL,并有一个问题。

将Python与SQLite3结合使用,我编写了以下代码:

# Use sqlite3 in the fileimport sqlite3# Create people.db if it doesn''t exist or connect to it if it does existwith sqlite3.connect("people.db") as connection:    c = connection.cursor()    # Create new table called people    c.execute("""CREATE TABLE IF NOT EXISTS people(firstname TEXT, lastname TEXT, age INT, occupation TEXT)""")    people_list = [        (''Simon'', ''Doe'', 20, ''Python Master''),        (''John'', ''Doe'', 50, ''Java Master''),        (''Jane'', ''Doe'', 30, ''C++ Master''),        (''Smelly'', ''Doe'', 2, ''Shower Master'')    ]    # Insert dummy data into the table    c.executemany("""INSERT INTO people(firstname, lastname, age, occupation) VALUES(?, ?, ?, ?)""", people_list)

我注意到我可以使用for循环而不是executemany来做同样的事情:

# Use sqlite3 in the fileimport sqlite3# Create people.db if it doesn''t exist or connect to it if it does existwith sqlite3.connect("people.db") as connection:    c = connection.cursor()# Create new table called peoplec.execute("""CREATE TABLE IF NOT EXISTS people(firstname TEXT, lastname TEXT, age INT, occupation TEXT)""")people_list = [    (''Simon'', ''Doe'', 20, ''Python Master''),    (''John'', ''Doe'', 50, ''Java Master''),    (''Jane'', ''Doe'', 30, ''C++ Master''),    (''Smelly'', ''Doe'', 2, ''Shower Master'')]# Insert dummy data into the tablefor person in people_list:    c.execute("""INSERT INTO people(firstname, lastname, age, occupation) VALUES(?, ?, ?, ?)""", person)

我只是想知道哪个更有效,更经常使用?

答案1

小编典典

批处理插入executemany会更有效,并且随着记录数量的增加,性能差异通常会很大。执行insert语句会产生大量开销,如果您一次插入一行,则会一遍又一遍地产生该开销。

只要简单易行,就应该选择批处理插入。

在某些情况下,编写一次插入
一行的算法可能要简单得多。例如,如果您一次从某处接收数据,则在获取数据
时仅插入它可能会更简单,而不是
在保存大量
数据时先建立列表并进行一次插入。在这种情况下,您需要考虑性能
和代码简单性之间的权衡。通常最好从简单的
方法开始(一次插入一行),然后仅
在发现其性能不佳时才对其他内容进行优化。

JDBC 中的execute()、executeQuery() 和executeUpdate() 方法有什么区别?

JDBC 中的execute()、executeQuery() 和executeUpdate() 方法有什么区别?

jdbc 中的execute()、executequery() 和executeupdate() 方法有什么区别?

一旦您创建了语句对象,您可以使用Statement接口的execute()、executeUpdate()和executeQuery()方法之一来执行它。

execute()方法:该方法用于执行SQL DDL语句,它返回一个布尔值,指定是否可以检索到ResultSet对象。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Example {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();

      //Executing the statement
      String createTable = "CREATE TABLE Employee( "
         + "Name VARCHAR(255), "
         + "Salary INT NOT NULL, "
         + "Location VARCHAR(255))";
      boolean bool = stmt.execute(createTable);

      System.out.println(bool);
   }
}
登录后复制

输出

Connection established......
false
登录后复制

executeUpdate(): 这个方法用于执行插入、更新、删除等语句。它返回一个整数值,表示受影响的行数。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ExecuteUpdateExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
     
      String insertData = "INSERT INTO Employee("
         + "Name, Salary, Location) VALUES "
         + "('Amit', 30000, 'Hyderabad'), "
         + "('Kalyan', 40000, 'Vishakhapatnam'), "
         + "('Renuka', 50000, 'Delhi'), "
         + "('Archana', 15000, 'Mumbai')";

      int i = stmt.executeUpdate(insertData);
      System.out.println("Rows inserted: "+i);
   }
}
登录后复制

输出

Connection established......
Rows inserted: 4
登录后复制

executeQuery():此方法用于执行返回表格数据的语句(例如 select)。它返回 ResultSet 类的对象。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ExecuteQueryExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();

      //Retrieving data
      ResultSet rs = stmt.executeQuery("Select *from Employee");

      while(rs.next()) {
         System.out.print("Name: "+rs.getString("Name")+", ");
         System.out.print("Salary: "+rs.getInt("Salary")+", ");
         System.out.print("City: "+rs.getString("Location"));
         System.out.println();
      }
   }
}
登录后复制

输出

Connection established......
Name: Amit, Salary: 30000, City: Hyderabad
Name: Kalyan, Salary: 40000, City: Vishakhapatnam
Name: Renuka, Salary: 50000, City: Delhi
Name: Archana, Salary: 15000, City: Mumbai
登录后复制

以上就是JDBC 中的execute()、executeQuery() 和executeUpdate() 方法有什么区别?的详细内容,更多请关注php中文网其它相关文章!

Making SQLITE/SQLITE3 executable scripts

Making SQLITE/SQLITE3 executable scripts

Use "here document" statements to build complex script files with embedded sql statements via the sqlite/sqlite3 utility.

#! /usr/bin/env bash

# execute some bash scripting commands here

sqlite3 mydatabase <<sql_ENTRY_TAG_1
SELECT * 
  FROM mytable 
  WHERE somecondition='somevalue';
sql_ENTRY_TAG_1

# execute other bash scripting commands here

sql_ENTRY_TAG_2
SELECT *
  FROM myothertable
  WHERE someothercondition='someothervalue';
sql_ENTRY_TAG_2

Note that being in a bash script means that you can expand $-variables inside the sql code directly. This is,however,not advised unless you can be sure that only trusted,competent people will run your code. Otherwise you'll be facing sql injection attacks.

我们今天的关于我无法让Python的executemany使sqlite3正常工作的分享就到这里,谢谢您的阅读,如果想了解更多关于Cursor fastexecutemany error: ('HY000', '[HY000] [Microsoft][SQL Server Native Client 11.0]Unicode 转换失败 (0) (SQLExecute)')、For循环或executemany-Python和SQLite3、JDBC 中的execute()、executeQuery() 和executeUpdate() 方法有什么区别?、Making SQLITE/SQLITE3 executable scripts的相关信息,可以在本站进行搜索。

本文标签: