Insert into mysql a python list - python

I tried many times to solve my problem with other questions in stackoverflow with no success. I'm learning python right now.
I know how to do it in PHP but I need to do it in python.
I have a table dentistas with 4 columns id, web, email, telefono.
And I import from another file with a list containing web urls.
I want to insert those websurls in the web column.
The code that im using right now doesn't shows me an error in the terminal, but doesn't insert anything to the table:
# coding=utf-8
import MySQLdb
from parser import lista
bd = MySQLdb.connect('localhost', 'testuser', 'test123', 'leads') # Connecting to the database
cursor = bd.cursor() # Creating the cursor
for x in lista:
cursor.execute("INSERT INTO dentistas(web) VALUES(%s)", (x,))

You forgot to commit() and save your current database state.
Try using bd.commit() after the loop.

Related

How can I make an id column in MYSQL which has auto increment using python?

I am using Python in CentOS and I`m doing a simple code to link python to MYSQL. My problem is I want to auto increment the id column. I use CentOS terminal .
I tried to write this so the program increments id column automatically because I saw it in some answer
record = [12,'tom']
cursor.execute("insert into t3(number,sent)values(%s,%s),record)
it give me the ERROR
<module> cursor.execute("insert into t3(number,sent)values(%s,%s)",record)
NameError :name 'cursor' is not defined
So guys please it`s my first experience in stack overflow I hope to find good answer. :(
Read the error. Have you defined a cursor variable?
Assuming you're using the mysql module, once you create your database object you can use it to create a cursor.
import mysql.connector
database = mysql.connector.connect(host="localhost", user="username", passwd="password", database="nameofdatabase")
cursor = database.cursor()
record = [12,'tom']
cursor.execute("INSERT INTO t3(number,sent) VALUES(%s,%s)", record)
Hope I could help, but if not try being more specific. Maybe posting all of your code?

from sql server to pandas dataframe with pyodbc - while working with small tables, it gives an error on complex sql queries

1 step: Create a temporary table with pyodbc into sql server for objects
2 step: Select objects from temporary table and load it into pandas dataframe
3 step: print dataframe
for creating a temporary table i work with pyodbc cursor as it trohws errors with pandas.read_sql command. wheras it trohws an error if i try to convert the cursor into a pandas dataframe. even with the special line for handling tuples into dataframes.
my program to connect, create, read and print which works as long as the query stays simple as it is now. (my actual approach has a few hundred lines of sql query statement)
import codecs
import os
import io
import pandas as pd
import pyodbc as po
server = 'sql_server'
database = 'sql_database'
connection = po.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes;')
cursor = connection.cursor()
query1 = """
CREATE TABLE #ttobject (object_nr varchar(6), change_date datetime)
INSERT INTO #ttobject (object_nr)
VALUES
('112211'),
('113311'),
('114411');
"""
query2 = """
SELECT *
FROM #ttobject
Drop table if exists #ttobject
"""
cursor.execute(query1)
df = pd.read_sql_query(query2, connection)
print(df)
Because of the lenght of the actually query i save you the trouble but instead post here the error code:
('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt (0) (SQLExecDirectW)')
This error gets thrown at query2 which is a multiple select statement with some joins and pivote functions
When I'm trying to put everything into one cursor i got issues with converting it from cursor to DataFrame (tried several methodes, maybe someone knows one which isn't on SO already or has a special title so i couldn't find it)
same problem if I'm trying to only use pd.read_sql then the creation of the temporary table is not working
I don't know where to go on from here.
Please let me know if i can assist you with further details which i may overwatched in accordance to my lostlyness :S
23.5.19 Further investigating:
According to Gord i tried to add autocommit to true which will work
for simple sql statements but not for my really long and
timeconsuming one.
Secondly i tried to add
"cursor.execute('SET NOCOUNT ON; EXEC schema.proc #muted = 1')
At the moment i guess that the first query takes longer so python already starting with the second and therefore the connection is
blocked. Or that the first query is returing some feedback so python
thinks it is finished before it actually is.
Added a time.sleep(100) after ececution of first query but still getting the hstmt is busy error. Wondering why this is becaus it should have had enough time to process the first
Funfact: The query is running smoothly as long as I'm not trying to output any result from it

sql INSERT in python (postgres, cursor, execute)

I had no problem with SELECTing data in python from postgres database using cursor/execute. Just changed the sql to INSERT a row but nothing is inserted to DB. Can anyone let me know what should be modified? A little confused because everything is the same except for the sql statement.
<!-- language: python -->
#app.route("/addcontact")
def addcontact():
# this connection/cursor setting showed no problem so far
conn = pg.connect(conn_str)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
sql = f"INSERT INTO jna (sid, phone, email) VALUES ('123','123','123')"
cur.execute(sql)
return redirect("/contacts")
first look at your table setup and make sure your variables are named right in the right order, format and all that, if your not logging into the specific database on the sql server it won't know where the table is, you might need to send something like 'USE databasename' before you do your insert statement so your computer is in the right place in the server.
I might not be up to date with the language but is that 'f' supposed to be right before the quotes? if thats in ur code that'd probably throw an error unless it has a use im not aware of or its not relevant to the problem.
You have to commit your transaction by adding the line below after execute(sql)
conn.commit()
Ref: Using INSERT with a PostgreSQL Database using Python

insert mysql table from python function

I'm very newbie to python and how its mysql connector works in any web application. I want to try something easy actually but got no idea how to work it out. I have this simple python script to make random numbers and allocate it in a variable. (numbers.py)
import random
number = random.radint(1,1000)
print number
and this very simple python script to make a table in a mysql database (try.py)
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Table_Try")
cur.execute("CREATE TABLE Table_Try(Value INT)")
My question is how do I insert the field "Value" with the value from variable "number" in number.py, since they are different scripts. When the value is inserted, how do I displayed in a php page so it can show random values repeatedly in a endless loop when opened? I have searched tutorial links about this in google but none could answer my problem here.
you can insert values into the database as follows:
c.execute("INSERT INTO db_name.Table(value) VALUES(%s)",[5])
In the above code c is my cursor and Table is my table in that database.
If you want to insert many values you can use executemany instead of execue

Python MySQLdb, simple chatroom/guestbook app

I've browsed some of the other questions about MySQL and Python on SO. There are a few things eluding me, because I'm pretty new to Python.
First, I'm trying to get a simple guestbook app to work. It takes posted variables and puts them into a MySQL database. Take a look:
con = MySQLdb.connect (host = "localhost",
user = "Chat",
passwd = "myPass",
db = "Chatserver")
cursor = con.cursor()
cursor.execute ("INSERT INTO guestbook (name,message) VALUES(%s,%s)",(name,greeting))
Ok, so some of the tutorials and answers on SO have many Quotation marks surrounding the SQL query, and I don't know why that is. I've tried it with 1 quote, I've tried it with 3 quotes, and it just never works. There are no exception callbacks and the code seems to run, but no records are ever entered into the database.
So my two questions are, how many quotation marks do I need when encapsulating the Queries, and why doesn't my script add anything to the database but not report any errors?
Ok, this answer Can't execute an INSERT statement in a Python script via MySQLdb helped me figure it out.
You have to add this at the end of your query.
cursor.execute(...)
con.commit() //this is what makes it actually do the execution?

Categories