Python conexión a MYSQL
Solapas principales
texto:
#!/usr/bin/python import pymysql #Conexion by Socket MAMP (ok!!!) db = pymysql.connect(db='conexion', user='root', passwd='root', unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', port= '8889') #Conexion by Socket XAMPP (ok!!!) # EN XAMPP HAY QUE HABILITAR EL SOCKET EN EL PHP.INI (XAMPP/etc/php.ini) # DESCOMENTAR LA LINEA (extension=php_sockets.dll) # PONER EL PUERTO YO LO TENGO CAMBIADO A 3307 # Y CREAR UNA BASE DE DATOS conexion db = pymysql.connect(db='conexion', user='root', passwd='', unix_socket='/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock', port= '3306') #CURSOR SE UTILIZA PARA MANIPULAR BD,# prepare a cursor object using cursor() method cursor = db.cursor() #CREACION DE TABLA cursor.execute("CREATE TABLE product(nombre VARCHAR(50), precio VARCHAR(20),seccion VARCHAR(20))") # Prepare SQL query to INSERT a record into the database. ## sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" ## val = ("Juan", "redes") sql = "INSERT INTO product (nombre, precio, seccion) VALUES (%s, %s, %s)" val = [ ('Camisa', '400','ropa' ), ('adidas', '90', 'sport'), ('adidasis', '80', 'sporting'), ] try: # Execute the SQL command #cursor.execute(sql,val) (para insertar 1 registro) cursor.executemany() para insertar multiples registros cursor.executemany(sql, val) # Commit your changes in the database db.commit() # imprime en pantalla el numero de registros insertados en la db print(cursor.rowcount, "record inserted.") except: # Rollback in case there is any error db.rollback() # desconectar del servidor db.close()
- Inicie sesión o regístrese para comentar
- 1411 lecturas