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))
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
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)"
I have this code to import my csv to mysql database:
import csv
import mysql.connector
import re
change = "hello"
mydb = mysql.connector.connect(user='root', password='',
host='localhost',
database='jeremy_db')
file = open('C:\\Users\\trendMICRO\\Desktop\\OJT\\test.csv', 'rb')
csv_data = csv.reader(file)
mycursor = mydb.cursor()
cursor = mydb.cursor()
for row in csv_data:
cursor.execute('INSERT INTO table_test(col1,col2,col3,col4)' 'VALUES(%s, %s, %s, %s)',row)
mydb.commit()
cursor.close()
print("Done")
Can I change the values of %s into my variable change = "hello"?
Please help me I'm new to python, I tried every solution but I can't find how to change the values. I tried this VALUES(hello, %s, %s, %s)',row) but it doesn't work
For this very particular case, you'd simply hardcode the value in the query:
cursor.execute('INSERT INTO ... VALUES ("hello", %s, %s, %s)', row)
Now you have only three placeholders in your query though, so you need to ensure that row is a list with three items. E.g.:
cursor.execute('INSERT INTO ... VALUES ("hello", %s, %s, %s)', row[1:])
If you really wanted to use a variable, you could do something like:
row[0] = change
cursor.execute('INSERT INTO ... VALUES (%s, %s, %s, %s)', row)
Or:
cursor.execute('INSERT INTO ... VALUES (%s, %s, %s, %s)', [change] + row[1:])
I'm trying to insert data that's already in one mysql table into another, using python. The column names are the same in each table, and objkey is the distinguishing piece of data I have for the item that I'd like to use to tell mysql which columns to look at.
import MySQLdb
db = MySQLdb.connect(host='', user='', passwd='', db='')
cursor = db.cursor
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))
cursor.execute(sql)
db.commit()
db.close()
It says I have a syntax error, but I'm not sure where since I'm pretty sure there should be parentheses around the field names the first time but not the second one. Anyone know what I'm doing wrong?
I'm not exactly sure what you are trying to do with the obj = repr(objkey) line, but python is thinking you are defining variables with this line, not setting sql syntax (if that is indeed your desire here).
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))
should probably be changed to something like:
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE obj=%;" % ((name, desig, data, num), name, desig, data, num, repr(objkey))
But even then, you would need objkey defined somewhere as a python variable.
This answer may be way off, but you need to defined what you are expecting to achieve with obj = repr(objkey), in order to get more accurate answers.
I've run into a problem while trying to execute an insert statement from python.
Here is my function definition:
def fill_course(param_string):
ar = param_string.split("|")
db = connect()
sql = (
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
)
data = ar[0], ar[1], ar[2]
cursor = db.cursor()
cursor.execute(sql, data)
db.commit()
if cursor.rowcount == 0:
res = 0
elif cursor.rowcount == 1:
res = 1
db.close()
print(res)
return res
I've followed this link as a reference.
The error I am getting is :
File "database.py", line 25
"INSERT INTO COURSE "VALUES (%s, %s, %s)"
^
SyntaxError: invalid syntax
I am not able to understand which part of the syntax is wrong here?
Please write the following string
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
like below:
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) VALUES (%s, %s, %s)"
or concatenate the two strings. As it is now, there is a syntax error.