Was trying to set time and the other value to record table but showing: Unknown column 'time' in 'field list', I define time into VARCHAR(255) AND make the value specific to "e" because it is char type, can anyone here help me out with this, much appreciated
import mysql.connector
import datetime
d = datetime.datetime.now()
e = d.strftime("%Y-%m-%d %H:%M:%S")
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="asd619248636",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.excute=("CREATE TABLE record (temperature FLOAT(20) , humidity FLOAT(20), time VARCHAR(255))")
#mycursor.execute("SHOW TABLES")
#for x in mycursor:
#print(x)
sql = "INSERT INTO record (temperature,humidity,time) VALUES (%s, %s, %s)"
val = (3.2,6.5,"e")
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
I think time is a keyword in mysql according to this
So in order to use it as a column name you will need to enclose it with backticks:
create_table_sql = "CREATE TABLE record (temperature FLOAT(20) , humidity FLOAT(20), `time` VARCHAR(255))"
sql = "INSERT INTO record (temperature,humidity,`time`) VALUES (%s, %s, %s)"
Related
I have created a table named 'Patient':
import mysql.connector as mysql
db=mysql.connect(host="localhost", user="root", password="xxxx",
database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-','3L','M',
'2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
And I'm getting the output as:
DataError: Column count doesn't match value count at row 1
Can you please help me find the error?
I'm sorry if you think I'm asking a silly question, I'm just in 11th grade, and this topic wasn't taught to us. I'm trying to learn this on my own...
There are too many problems in your script. Your number of parameters don't match.
import mysql.connector as mysql
db = mysql.connect(host="localhost", user="root",
password="xxxx",database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender,Date)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-
','3L','M','2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
It was an easy fix. Hope that you find it useful
my plan is to insert the date (day_of_test) into a MySql database, where the dataformat is referenced as a Date.
I have to keep the syntax in the format you see below. But unfortunately my attempts to store specifically the date as a string within the sytax VALUES(%s...) don't seem to work.
Does anyone know the easiest way to adjust my syntax to insert day_of_test successfully?
Thank you all very much
import mysql.connector
mydb = mysql.connector.connect(host="34.xxx.xxx.xxx", user="xxxx", password="xxxxx", database='btc-analysis-db')
c = mydb.cursor()
btc_est = 150.2
sap_close = 100.23
gold_close = 120.2
bonds_close = 210.12
btc_actual = 130.12
day_of_test = "2022-04-20"
c = mydb.cursor()
c.execute(
"INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`, `gold_close`, `btc_actual`) VALUES (%s, %d, %d, %d, %d, %d);" % (
day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))
mydb.commit()
c.execute("select * from ML1")
result = c.fetchall()
If you are using python string formating, then you are missing quotation marqs around the value for date, and your sintax should be:
c.execute(
"INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`,
`gold_close`, `btc_actual`) VALUES ('%s', %d, %d, %d, %d, %d);" % (
day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))
But you shouldn´t do it that way. you should use prepared statements (to avoid SQL injection an other problems), and your sintax should be like this:
c.execute(
"INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`,
`gold_close`, `btc_actual`) VALUES (%s, %s, %s, %s, %s, %s);", (
day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))
I want to create a dataframe and update it to mysql.
If there is a duplicate key, it will be updated and if there is no duplicate key, it will be inserted.
user = 'test'
passw = '...'
host = '...'
port = '...'
database = '...'
conn = pymysql.connect(host=host,
port=port,
user=user,
password=passw,
database=database,
charset='utf8')
curs = conn.cursor()
data = list(dataframe.itertuples(index=False, name=None))
sql = "insert into naversbmapping(brand, startdate, enddate, cost, daycost) values (%s, %s, %s, %s, %s) on duplicate key update brand = %s, startdate = %s, enddate = %s, cost = %s, daycost = %s"
curs.executemany(sql, data)
conn.commit()
conn.close()
However, I get the following error. How do I fix it?
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, startdate = %s, enddate = %s, cost = %s, daycost = %s' at line 1")
)
You use following MySQL constriuct so that you don't need the data twice as you have the double number of values on your original, but are only sending it once
$sql = "INSERT INTO naversbmapping(brand, startdate, enddate, cost, daycost) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE brand = VALUES(brand), startdate = VALUES(startdate), enddate = VALUES(enddate), cost = VALUES(cost), daycost = VALUES(daycost)")
I need to install tupule value to database,but getting "Unknown column 'Mac' in 'field list'" error
Below is the code i used
import mysql.connector, csv, sys
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="mydjangoapp",
port=3307,
)
cursor=conn.cursor()
t1=('Mac', 'Mohan')
sql="insert into books (title,isbn) values(%s,%s)" %t1
cursor.execute(sql)
Don't use % interpolation, use placeholders.
t1 = ('Mac', 'Mohan',)
cursor.execute("INSERT INTO books (title, isbn) VALUES (%s, %s)", t1)
I am building this array with 40k entries.
array = [(value1, value2, value3),(value1, value2, value3),(value1, value2, value3) .... ]
Is it possible to insert this into mysql in python something like:
cursor.execute('''INSERT IGNORE into %s VALUES *array here*''' % (table_name, array))
I am having trouble passing the array variable into mysql correctly. Any help appreciated.
Yes you can do it with executemany:
cursor.executemany('INSERT IGNORE into %s VALUES(%s, %s, %s)'%table_name, sql_data)
Note: you shouldn't use % to pass values to the database, instead you need to pass them in the second parameter of execute/executemany. i used % for the table name because the first parameter is the prepared query string.
This is Use for me try it.
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="test"
)
mycursor = mydb.cursor()
print("Insert Process... Please Wait...")
for r in range(1,tdrows+1):
a = []
for c in range(1,tdcols+1):
a.append(driver.find_element_by_xpath("//*[#id='DataTables_Table_0']/tbody/tr["+str(r)+"]/td["+str(c)+"]").text)
sql = "INSERT IGNORE into test_table(id,fname,lname) VALUES (%s, %s, %s)"
val = (a)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "Record Inserted.")