from sqlalchemy import create_enginemy_conn = INTO `database_name`.`student` (`name` ,`class` ,`mark` ,`sex`) VALUES(%s,%s,%s,%s)"my_data=('King','Five',45,'male')id=my_conn.execute(query,my_data)print("ID of Row Added = ",id.lastrowid)Output ID of Row Added = 45 Using multiple records to add from sqlalchemy import create_enginemy_conn = query="INSERT INTO `database_name`.`student` (`name` ,`class` ,`mark` ,`sex`) VALUES(%s,%s,%s,%s)" my_data= id=my_conn.execute(query,my_data) print("Rows Added = ",id.rowcount)except: print("Database error ")Output Rows Added = 3 Capturing error message This is required to prevent injection attack. from sqlalchemy import create_enginemy_conn = INTO `database_name`.`student` (`name` ,`class` ,`mark` ,`sex`) \ VALUES ('King1', 'Five', '45', 'male')")print("ID of Row Added = ",id.lastrowid)Output ID of Row Added = 46 Using parameterized query to add recordAlways use parameterized query when the data is coming from unknown sources. We will collect this id after adding record to database. Use the code to create your sample student table.įrom sqlalchemy import create_enginemy_conn = INTO `database_name`.`student` (`name` ,`class` ,`mark` ,`sex`) \ VALUES ('King1', 'Five', '45', 'male')")print("Row Added = ",id.rowcount)Output Row Added = 1In our student table we have used one auto incremented id column. from sqlalchemy import create_enginemy_conn = create_engine("mysql mysqldb:// userid: database_name")We are using student table. In all the codes below replace userid, password and database_name with your MySQL login and database details. Insert record in MySQL database table using sqlalchemy We will use SQL INSERT to add a record to our database student table.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |