Error using pymssql when creating database users in SQL Server - python

I am getting the below error whenever I am trying to create a new user on a database.
Traceback (most recent call last):
File "src\pymssql\_pymssql.pyx", line 460, in pymssql._pymssql.Cursor.execute
File "src\pymssql\_mssql.pyx", line 1104, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql\_mssql.pyx", line 1135, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql\_mssql.pyx", line 1268, in pymssql._mssql.MSSQLConnection.format_and_run_query
File "src\pymssql\_mssql.pyx", line 1806, in pymssql._mssql.check_cancel_and_raise
File "src\pymssql\_mssql.pyx", line 1852, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (102, b"Incorrect syntax near 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_sqlserver.py", line 60, in <module>
createUsers(row[0][:-1], target_server, target_database)
File "test_sqlserver.py", line 44, in createUsers
cursor.execute('%s', sqlStatement)
File "src\pymssql\_pymssql.pyx", line 475, in pymssql._pymssql.Cursor.execute
pymssql._pymssql.ProgrammingError: (102, b"Incorrect syntax near 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
Below is my code currently.
def createUsers(sqlStatement, server, database):
conn = pymssql.connect(server=server, database=database)
cursor = conn.cursor()
cursor.execute('%s', sqlStatement)
target_server = 'MYServer'
target_database = 'MYDatabase'
sqlStatement = 'CREATE USER [test_login] FOR LOGIN [test_login] WITH DEFAULT_SCHEMA=[dbo]'
createUsers(sqlStatement, target_server, target_database)
I am not sure why I am getting this error as I can execute the SQL statement directly on the database without any issues. And I can also use pymssql to query information from the database. But whenever I try to create a new user on the database, I keep getting this error. Is anyone familiar with this?

Issue was resolved after changing cursor.execute statement to below
cursor.execute(sqlStatement)
I also had to add the below commit, otherwise the changes were not being seen on the database side.
conn.commit()

Related

Cannot connect Python to MySQL on a hosting. ERROR 1227 (42000), ERROR 1227 (42000)

I make a telegram bot using python and MySQL. I can enter the database in terminal, but when I run my python code, it says I have no permission.
ilyacherne#vh289 ~ $ python3 /home/i/ilyacherne/public_html/cgi-bin/bot.py
Traceback (most recent call last):
File "/home/i/ilyacherne/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 239, in _open_connection
self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Access denied for user 'ilyacherne'#'77.222.61.25' (using password: YES)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/i/ilyacherne/public_html/cgi-bin/bot.py", line 3, in <module>
import config
File "/home/i/ilyacherne/public_html/cgi-bin/config.py", line 8, in <module>
database = mysql.connect(
File "/home/i/ilyacherne/.local/lib/python3.8/site-packages/mysql/connector/__init__.py", line 272, in connect
return CMySQLConnection(*args, **kwargs)
File "/home/i/ilyacherne/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 85, in __init__
self.connect(**kwargs)
File "/home/i/ilyacherne/.local/lib/python3.8/site-packages/mysql/connector/abstracts.py", line 1009, in connect
self._open_connection()
File "/home/i/ilyacherne/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 241, in _open_connection
raise errors.get_mysql_exception(msg=exc.msg, errno=exc.errno,
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'ilyacherne'#'77.222.61.25' (using password: YES)
I checked the password, host name, database name and user.
I connect with this code:
database = mysql.connect(
host = '77.222.61.25',
user = 'ilyacherne',
passwd = 'CENSORED',
database = 'ilyacherne'
)
support said that MySql 5.7 connects to socket by default and i connect just with 'sudo mysql', and then they reccomended me try this:
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password'; FLUSH PRIVILEGES;
but it says:
ERROR 1227 (42000): Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation
ERROR 1227 (42000): Access denied; you need (at least one of) the RELOAD privilege(s) for this operation
Pip install mysql-connector-python
Then import mysql-connector.

Using Python to access SQL Server SQL Database on Azure Gives an Error

I am trying to use the pymssql module in Python to access a SQL Server SQL Database. However, my code gives a traceback error when I run my code on Ubuntu Linux. BTW, the system is actually a Microsoft Azure VM.
Below is my code:
import pymssql
connection1 = pymssql.connect(
server = 'redworth-test-sql.database.windows.net',
user = '*********#redworth-test-sql',
password = '**********',
database = 'redworth-test-sql-database'
)
sql = connection1.cursor()
cursor.execute('insert into table1 values (\'Rohit\', \'Karthik\', \'2006/08/02\')')
allRows = sql.fetchall()
print(allRows)
connection1.close()
(I am using a * for my username & password for security reasons, but my code on my computer has the actual strings)
(I have also installed my pymssql module on python3 using pip as well)
But running that code gives me the following error on my system:
Traceback (most recent call last):
File "src/pymssql.pyx", line 636, in pymssql.connect
File "src/_mssql.pyx", line 1957, in _mssql.connect
File "src/_mssql.pyx", line 676, in _mssql.MSSQLConnection.__init__
File "src/_mssql.pyx", line 1683, in _mssql.maybe_raise_MSSQLDatabaseException
_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (redworth-test-sql.database.windows.net:1433)\n')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyMsSQL.py", line 7, in <module>
database = 'redworth-test-sql-database'
File "src/pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (redworth-test-sql.database.windows.net:1433)\n')
I am not sure what is causing this error.
Thank you in advance for your help.
Congratulations that pyodbc works for you.
Azure document all suggest us using pyodbc to connect to the Azure SQL database, bellow is the example:
import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Ref: Create(Python) code to query your database.
Hope this helps.

Read table from MySQL - Python

I have MySQL ( Database: items, Table: issuelist )
I want to read and print out by python... but when I run code as below, it show error.
import mysql.connector
#from mysql.connector import Error
mydb = mysql.connector.connect(
host="localhost",
#user="yourusername",
#passwd="yourpassword",
database="items"
)
mycursor = mydb.cursor()
sql_statement = "SELECT * FROM issuelist"
mycursor.execute(sql_statement)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Traceback (most recent call last): File
"C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelMySQL.py",
line 8, in
database="items" File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector__init__.py",
line 219, in connect
return MySQLConnection(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 104, in init
self.connect(**kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\abstracts.py",
line 960, in connect
self._open_connection() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 292, in _open_connection
self._ssl, self._conn_attrs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 212, in _do_auth
self._auth_switch_request(username, password) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection.py",
line 256, in _auth_switch_request
raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied
for user ''#'localhost' (using password: NO)
How to do resolve ?
Thanks you so much!
The error message is quite explanatory :
Access denied for user ''#'localhost' (using password: NO)
You can't just connect to mysql with no account...
The error msg clearly shows the mistake -- The connect info is not correct. That is ,in your code, make sure the info of the host,user,passwd and database are all correct?

How to add a record to a table in MySQL using python?

In my code, I am trying to insert data into the 'user_attempts' table of my DB which has two fields: attemptID (auto-incremented) and username. Therefore when I'm passing data in I only have to pass the username as the attemptID is generated by MySQL. This my code:
username='test1'
add_userattempt=mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
mydb.commit()
However it returns this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 266, in <module>
reviewPage(screen) # the home screen function is called which essentially starts the whole program.
File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 132, in reviewPage
add_userattempt=mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 590, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 478, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 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 ''test1'' at line 1
As shown by the error you get, you have a syntax error in your SQL code.
Instead of
mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
it should be
mycursor.execute('INSERT INTO user_attempt(username) VALUES(%s)', username)
This webpage here (https://www.mysqltutorial.org/python-mysql-insert/) explains the whole procedure of inserting data into MySQL tables using python pretty well.
Why do you declare your execute statement as a variable?
Hope this helps!

Python can't connect to MySQL db: OperationalError

When in the Python shell I type:
import MySQLdb
Con = MySQLdb.Connect(user='testuser', password='password', db='test')
And I get this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Nickey\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\__init__.py", line 86, in Connect
return Connection(*args, **kwargs)
File "C:\Users\Nickey\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\connections.py", line 204, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2059, <NULL>)
And no description of the error at all. Please, I am waiting for help. Thanks.
UPDATE: In case somebody will be having this problem, it appears to be connected with the new mysql_auth_plugin, with its new Strong Password Encryption for Authentication. I just switched to old_password_plugin(Legacy Authentication Method) in the configuration of MySQL Server and now [All works!].
According to the docs, password is not a keyword argument like you entered, instead it's passwd as you can see --> here

Categories