Python 3.6 & Inserting Values into MariaDB via variable - python

Code description - Running a program to add values to a maria db table. The program executes and prompts for the variables without error but the table shows no rows when I query it. Any idea where I am going wrong? Wanted to make it dynamic so I am using variables for the db and the table.
######## Output #########
[root#localhost student_program]# python db_setup.py
Connection successful!!
Database already exists: students
create_table
/usr/local/lib/python3.6/site-packages/pymysql/cursors.py:329: Warning: (1050, " Table 'students_info' already exists")
self._do_get_result()
use students;
Enter the first name :Frank
Enter the last name: Brady
Enter the email address: frank#noemail.com
Enter the address: 300 Main Street, Belfast
Enter the DOB in YYYY-MM-DD: 1980-02-02
Enter the english mark: 90
Enter the maths mark: 80
Enter the history mark: 70
Enter the science mark: 45
('INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);', ('Frank', 'Brady', 'frank#noemail.com', '300 Main Street, Belfast', '1980-02-02', '90', '80', '70', '45'))
######### Program below #################
import os,pymysql
mariadb_root = '/var/lib/mysql/'
db_to_create = 'students'
conn = pymysql.connect(host='localhost', user='xxx', passwd='xxx', cursorclass=pymysql.cursors.DictCursor)
print('Connection successful!!')
# Check if db exists, if not create
def check_db_exists():
dbfile = os.path.join(mariadb_root, db_to_create)
if not os.path.exists(dbfile):
cur = conn.cursor()
command = "CREATE DATABASE %s;" % db_to_create
print(command)
cur.execute(command)
print("Database created %s:", db_to_create)
else:
print("Database already exists: %s" % db_to_create)
check_db_exists()
def create_database():
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
create_table = ("""
CREATE TABLE IF NOT EXISTS students_info (
ID int NOT NULL AUTO_INCREMENT,
firstname varchar(255),
lastname varchar(255),
email varchar(255),
address varchar(255),
DOB DATE,
english varchar(255),
maths varchar(255),
history varchar(255),
science varchar(255),
PRIMARY KEY (ID));
""")
print("create_table")
cur.execute(create_table)
print(command)
create_database()
def add_student():
firstname = input("Enter the first name :")
lastname = input("Enter the last name: ")
email = input("Enter the email address: ")
address = input("Enter the address: ")
DOB = input("Enter the DOB in YYYY-MM-DD: ")
english = input("Enter the english mark: ")
maths = input("Enter the maths mark: ")
history = input("Enter the history mark: ")
science = input("Enter the science mark: ")
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
cur.execute = ("""INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);""",
(firstname,lastname,email,address, DOB,english,maths,history,science))
print(cur.execute)
cur.close()
conn.close()
add_student()

Related

sqlite3 | data doesn't save in table

The code works when I run it but when I run it again the data from the previous run is not saved, but the table is still there. I have tried many methods of saving the file and it still doesn't save
import sqlite3
conn = sqlite3.connect('conntact.db')
cursor = conn.cursor()
check = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='contacts'");
if check == 0:
cursor.execute('''CREATE TABLE contacts
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
EMAIL TEXT NOT NULL,
PHONE TEXT NOT NULL);''');
def add_contacts():
name1 = input("Enter contact name: ")
email1 = input("Enter contact email: ")
phone1 = input("Enter contact phone number: ")
id_s = input("Enter id: ")
cursor.execute("INSERT INTO contacts (ID, NAME,EMAIL,PHONE) VALUES (?,?,?,?)", (id_s, name1, email1, phone1));
def read_all_contact():
cursor.execute("SELECT * FROM contacts");
records = cursor.fetchall()
print(f"Total rows are: {len(records)}")
for row in records:
print(f'ID: {row[0]}')
print(f'Name: {row[1]}')
print(f'Email: {row[2]}')
print(f'Phone: {row[3]}\n')
add_contacts()
read_all_contact()
conn.close()
Any help would a apreciated
Remove check = ... line, which is wrong anyway.
Remove if check == 0
Replace "CREATE TABLE contacts" with "CREATE TABLE IF NOT EXISTS contacts"
Execute conn.commit()

While doing insertion in mysql using Python , getting an error as "Unknown Column in field list"

While trying to insert the Query in MYSql through python Script, I am facing an error as "1054 (42S22): Unknown column 'Abhinav' in 'field list'". There is some minor syntax error , but I am not able to Find it.
my_cursor.execute("CREATE DATABASE IF NOT EXISTS task")
my_cursor.execute("CREATE TABLE IF NOT EXISTS EmployeeList(user_id INT AUTO_INCREMENT PRIMARY KEY,EMPID INT, Emp_Name VARCHAR(100),Designation VARCHAR(100), Role VARCHAR(100), Updated_by VARCHAR(100), LastUpdate TIMESTAMP DEFAULT NOW())")
EMP_ID = input("Enter the Employement Id : ")
EmpName = input("Enter the Employee Name : ")
Designations = input("Enter the Designation : ")
Roles = input("Enter the Role : ")
Updatedby = input("Enter the name of the Person updated by: ")
try:
sql_insert_query = f"INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES ({EMP_ID},{EmpName},{Designations},{Roles},{Updatedby})"
my_cursor.execute(sql_insert_query)
mydb.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
finally:
if (mydb.is_connected()):
my_cursor.close()
mydb.close()
print("MySQL connection is closed")
user input details has to be given after running the script.
Enter the Employement Id : 1
Enter the Employee Name : Abhinav
Enter the Designation : Software Engineer
Enter the Role : GE
Enter the name of the Person updated by: Abhi
Error -
Failed to update record to database: 1064 (42000): 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 'Engineer,GE,Abhi)' at line 1
MySQL connection is closed
Rather than format the INSERT statement by hand, you should add placeholders and pass the actual values as params to the execute method:
sql_insert_query = "INSERT INTO EmployeeList(EMPID,Emp_Name,Designation,Role,Updated_by) VALUES (%s,%s,%s,%s,%s)"
my_cursor.execute(sql_insert_query, params=(EMP_ID, EmpName, Designations, Roles, Updatedby))
Here's some documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Want to insert data in MYSQL table by user command using python programming [duplicate]

This question already has answers here:
How can I insert data into a MySQL database?
(3 answers)
Closed 3 years ago.
I want to insert data in mysql table by user command. But i can't understand why cannot execute code. Code sample:
user_name= input("What is your name?:\n")
user_phone= input("What is your phone:\n")
user_city= input("Your city:\n")
myCursor.execute("insert into information(name,phone, city) values(user_name, user_phone, user_city);")
print("Insert successfully")
import pymysql
con = pymysql.connect("Host", "Username", "Password", "Database")
cur = con.cursor()
#taken from sample displayed
user_name = input("What is your name?:\n")
user_phone = int(input("What is your phone number:\n"))
user_city = input("Your city:\n")
cur.execute("insert into information(name,phone, city) values('{}', {},
'{}')".format(user_name, user_phone, user_city))
con.commit()
con.close()
you need to define below variables in order to use execute.
import cx_Oracle
DSN_TNS = cx_Oracle.makedsn(IP, PORT, SID)
DB_CRED = cx_Oracle.connect(USERNAME, PASSWORD, DSN_TNS)
curs = DB_CRED.cursor()
user_name= input("What is your name?:\n")
user_phone= input("What is your phone:\n")
user_city= input("Your city:\n")
sql_query = "insert into information(name,phone, city) values('{0}','{1}','{2}')".format(user_name, user_phone, user_city)
curs.execute(sql_query)
DB_CRED.commit()
DB_CRED.close()

To display department ID using department name in python with psycopg2?

With psycopg2 in python, I'm trying to retrieve department ID using department name for new employee details by inserting as raw query. But, I couldn't able to find any solution for this problem. Is there any solution for this problem which will help me to complete my task?
This is my employee database:
This is my python code:
import datetime
import psycopg2.extras
conn = psycopg2.connect(database="emp", user="postgres",
password="12345", host="127.0.0.1",
port="5432")
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
emp_name = str(input("Enter new employee name: "))
while True:
gender = str(input("Type your gender: "))
if gender == 'M' or gender == 'F':
break
hire_date = input("Enter hire date(YYYY-MM-DD): ")
year, month, day = map(int, hire_date.split('-'))
hiredate = datetime.date(year, month, day)
salary = str(int(input("Enter your salary: ")))
deptname = str(input("Enter department name: "))
cur.execute("INSERT INTO employee(emp_name, gender, hire_date, salary,
deptid) VALUES(%s, %s, %s, %s)",(emp_name, gender,hire_date, salary))
cur.execute("SELECT * FROM employee ORDER BY emp_no DESC LIMIT 1 WHERE
deptname = %(deptname)s", {'deptname': deptname})
rows = cur.fetchall()
print( '\n'.join( str( row ) for row in rows ) )
print( "Created successfully!" )
conn.commit()
conn.close()
To display department ID using department name can be achieved by this following query:
deptname = str(input("Enter department name: "))
cur.execute("SELECT deptid FROM department WHERE department.deptname = %("
"deptname)s", {'deptname': deptname})
deptid = cur.fetchone()
If you want only deptid, Use this.
cur.execute('''SELECT d.deptid FROM department d
WHERE d.deptname = %(deptname)s''', {'deptname': deptname})
If you want the details of all employees in that department
cur.execute('''SELECT e.* FROM employee e JOIN department d
ON d.deptid = e.deptid
WHERE d.deptname = %(deptname)s''', {'deptname': deptname})

Syntax error with python & sqlite3

I have a syntax problem using sqlite3 with Python around the last line of the below code:
playerName = input("Enter your name: ")
money = input("Enter credits: ")
conn = sqlite3.connect("highscore.db")
c = conn.cursor()
c.execute("CREATE TABLE players(name TEXT, money INTEGER)")
c.execute("INSERT INTO players VALUES('%s','%s')", playerName, money)
How can I resolve this ?
Change this line:
c.execute("INSERT INTO players VALUES('%s','%s')", playerName, money)
To:
c.execute("INSERT INTO players VALUES(?,?);",(playerName, money))

Categories