from config import * from mysql.connector import (connection) cnx = connection.MySQLConnection(user=USER, password=PW, host=HOST, database=DB) cnx.close()
import pandas as pd import os from mysql.connector import (connection) dir_path = os.getcwd() host = 'localhost' user = '******' pw = 'cdms' db = 'CDMSTest' data = pd.read_excel(dir_path + '/Continuity_PCB.xlsx') conn = connection.MySQLConnection(user=user, password=pw, host=host, database=db) cursor = conn.cursor() print(data) # DB 78 pin VIB pin Signal name Notes for index, row in data.iterrows(): str_input = """INSERT INTO channel_naming (Matrix_location, DB_78_pin, VIB_pin, Signal_name) VALUES ("{matr}", "{dpin}", "{vibpin}", "{sign}"); """ execute = str_input.format(matr=row["Matrix location"], dpin=row["DB 78 pin"], vibpin=row["VIB pin"], sign=row["Signal name"]) cursor.execute(execute) conn.commit() conn.close()
from mysql.connector import connection cnx = connection.MySQLConnection(user='******', password='******', host='127.0.0.1', database='fkdemo') mycursor = cnx.cursor() data1 = mycursor.execute("SELECT count(*) from categories") data = mycursor.fetchone() print("There are {} records in my database".format(data)) cnx.close()
#!/usr/bin/python3 from mysql.connector import connection import datetime import csv import glob import os import pdb cnx = connection.MySQLConnection(user="******", password='******', host='localhost', database='stockpredict') insert_stock = ( "INSERT INTO stocks " "(Site, Author, Title, Text, StartDate, EndDate)" "VALUES( %s, %s, %s, %s, %s, %s)" ) cursor = cnx.cursor() fcount = 0 for pathname in glob.glob('selectedData/*.txt'): fcount += 1 if count > 20: break # for testing, we try 20 files print("Processing", pathname) #name is first part of filename, this get stored into the record filename = os.path.basename(pathname) #1st get filename exclude directory name = filename.split('.')[0]
from mysql.connector import (connection) cnx = connection.MySQLConnection(user='******', password='******', host='mysqldb', port=3306, database='backend') cursor = cnx.cursor(buffered=True) cmd = ("show tables") cmd1 = "ALTER DATABASE backend CHARACTER SET utf8 COLLATE utf8_general_ci" cursor.execute(cmd1) cursor.execute(cmd) for table in cursor: cursor2 = cnx.cursor(buffered=True) cmd2 = "ALTER TABLE %s CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" % table[ 0] cmd3 = "ALTER TABLE %s DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci" % table[ 0] cursor2.execute(cmd2) cursor2.execute(cmd3) cnx.close()
from mysql.connector import connection DB_NAME = 'pydbE1x' cnx = connection.MySQLConnection(user='******', password='******',host='127.0.0.1') mycursor=cnx.cursor() mycursor.execute("create database {}".format(DB_NAME))
load_dotenv() config = { 'host': os.getenv('DB_HOST'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASS'), 'database': os.getenv('DB_NAME'), 'raise_on_warnings': True } add_role = ( "INSERT INTO `market_tracker`.`vt_role` " "(`skill`, `role_rank`, `rank_change`, `median_salary`, " "`median_change`, `historical_ads`, `ad_percentage`, `live_vacancies`) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)") cnx = connection.MySQLConnection(**config) cur = cnx.cursor() with open('data.csv', newline='') as fp: reader = csv.reader(fp) print('adding rows...') for row in reader: cur.execute(add_role, row) cnx.commit() print('commited changes...') cur.close() cnx.close() print('Done!')
def setUp(self): config = self.getMySQLConfig() self.cnx = connection.MySQLConnection(**config)
def setUp(self): config = self.getMySQLConfig() config['connection_timeout'] = 5 self.cnx = connection.MySQLConnection(**config)
from mysql.connector import (connection) cnx = connection.MySQLConnection( user='******', password='******', host='localhost', ) cnx.close()
def setUp(self): config = self.getMySQLConfig() cnx = connection.MySQLConnection(**config) cnx.cmd_query("DROP USER 'root'@'127.0.0.1'") cnx.cmd_query("DROP USER 'root'@'::1'") cnx.close()
from mysql.connector import (connection) cnx = connection.MySQLConnection(user='******', password='******', host='localhost', database='movies') cnx.close() print(cnx)
import mysql.connector conn = mysql.connector.connect(database='db01', user='******', password='******') print(type(conn)) conn.close() from mysql.connector import connection conn = connection.MySQLConnection(database='db01', user='******', password='******') conn.close() import mysql.connector config = {'database': 'db01', 'user': '******', 'password': '******'} conn = mysql.connector.connect(**config) conn.close()
import time, sys, math from grove.adc import ADC from mysql.connector import connection connexion = connection.MySQLConnection(user='******', host='127.0.0.1', database='plante') cursor = connexion.cursor() __all__ = ["GroveLightSensor"] class GroveLightSensor(object): def __init__(self, channel): self.channel = channel self.adc = ADC() @property def light(self): value = self.adc.read(self.channel) return value Grove = GroveLightSensor def main(): from grove.helper import SlotHelper sh = SlotHelper(SlotHelper.ADC) pin = sh.argv2pin()
from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.neural_network import MLPClassifier from sklearn.linear_model import SGDClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn import tree import matplotlib.pyplot as plt warnings.simplefilter("ignore") from sklearn import preprocessing import matplotlib.pyplot as plt connection = connection.MySQLConnection(user='******', password='******', host='localhost', database='football') cursor = connection.cursor() try: cnx = mysql.connector.connect(user='******', password='******', database='football') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print("you are connected")
def setUp(self): config = tests.get_mysql_config() config['raw'] = True self.connection = connection.MySQLConnection(**config) self.cur = self.connection.cursor()
ENTITY_CATEGORY = 'WikiData.KB.100d' DIM = 100 class WikiLabel(object): """docstring for WikiLabel""" def __init__(self, id:int, label:str, title:str): self.id = id self.label = label self.title = title def __repr__(self): return 'Wikidata[id={}, label={}, title={}]'.format(self.id, self.label, self.title) from mysql.connector import (connection) cnx = connection.MySQLConnection(user='******', password='******', host='10.2.2.60', database='wikidata') def list_wiki_labels(start_id:int, size:int)->List[WikiLabel]: results = [] query = ("SELECT id, label, title_en_lower FROM label_title " "WHERE id BETWEEN %s AND %s AND INSTR(`title_en`, ' ') = 0") end_id = start_id + size - 1 print('loading wiki_labels[{}, {}]...'.format(start_id, end_id)) cursor = cnx.cursor() cursor.execute(query, (start_id, end_id)) for mid, label, title_en_lower in cursor: if title_en_lower.isalnum(): wl = WikiLabel(mid, label, title_en_lower) results.append(wl)
def setUp(self): config = tests.get_mysql_config() config['raw'] = True config['buffered'] = True self.cnx = connection.MySQLConnection(**config)
def add(): if request.method == 'POST': tstcategory = request.form['testcategory'] tstname = request.form['testname'] tstsuite = request.form['testsuite'] tstscript = request.form['testscript'] tstdescription = request.form['description'] tstnooftests = request.form['no.of.tests'] try: # initDb() db = MySQLdb.connect(host='10.130.163.64', user='******', passwd='Password@123', db='tcdata', port='3309') # myConnection = mysql.connector.connect(host='10.130.163.64', user='******', passwd='Password@123', db='tcdata', port='3309') # cur = myConnection.cursor() # conn = MongoClient('mongodb://*****:*****@TCTINFRA:27017') print("Connected successfully!!!") except: print("Could not connect to mysql") sql_insert_query = """ INSERT INTO tctestdata (uid, category ,testname, testscript, no_of_tests, fullcycle, automationstatus, automationtype, canbeMgpu, isMgpu, execution_time_in_min, coverageDate) VALUES('2', tstcategory, tstname, tstsuite, tstscript, tstnooftests, 'fullyautomated', 'e2e', 'yes', 'no', '20', '2018-01-11');""" # db = MySQLdb.connect(host='10.130.163.64', user='******', passwd='Password@123', db='tcdata', port=3309) db = connection.MySQLConnection(host='10.130.163.64', user='******', passwd='Password@123', db='tcdata', port=3309) # myConnection = mysql.connector.connect(host='10.130.163.64', user='******', passwd='Password@123', db='tcdata', port='3309') #cursor = myConnection.cursor() cursor = db.cursor() result = cursor.execute(sql_insert_query) db.commit() # myConnection.commit() print("Record inserted successfully into python_users table") val = "Test added successfully" # db = conn.tcdata # collection = db.tctestdata # tcCategory = request.form['testcategory'] # emp_rec1={"uid":"11", "category":tstcategory, "testname":tstname, "testscript":tstscript, "no_of_tests":tstnooftests, "os_applicability": { # "centOS":"Yes", # "ubuntu1604":"Yes", # "ubuntu1804":"Yes" # }, # "applicable_category": { # "sanity":"Yes", # "regression":"Yes", # "performance":"Yes", # "release":"Yes" # }, # "fullcycle":"Yes", # "automation_status":"FullyAutomated", # "automation_type": "skynetE2E", # "CanbeMgpu":"0.1", # "IsMgpu":"0.1", # "execution_time_in_min": "1", # "coverageDate":"0.1" # } # rec_id1 = collection.insert_one(emp_rec1) # print("Record inserted in the collection", rec_id1) # return render_template({'key_val':val}) return val else: return render_template('add.html')
# -*- coding: utf-8 -*- import json from mysql.connector import (connection) import MeCab import operator mecab = MeCab.Tagger("-Ochasen") with open('./preprocessing/config.json') as config_file: data = json.load(config_file) cnx = connection.MySQLConnection(user=data['mysql']['user'], password=data['mysql']['passwd'], host=data['mysql']['host'], database=data['mysql']['db']) cursor = cnx.cursor() query = ( "SELECT entry_id, description FROM cs_entry_comment WHERE entry_id IS NOT NULL AND status IN (1,2)" ) cursor.execute(query) words = {} total = 0 for (entry_id, description) in cursor: print(entry_id) total += 1 node = mecab.parseToNode(description.encode('utf-8'))
'tid': value[1] } # Fetch image entity data by id. query = 'SELECT vid, langcode, name FROM taxonomy_term_field_data WHERE tid=' + str(value[1]) cursor.execute(query, nid) term_values = cursor.fetchone() result[value[0]]['vid'] = term_values[0] result[value[0]]['langcode'] = term_values[1] result[value[0]]['name'] = term_values[2] return result cnx = connection.MySQLConnection(user='******', password='******', host='127.0.0.1', database='dbname') cursor = cnx.cursor() query = 'SELECT nid, title, status, created, changed, langcode FROM node_field_data WHERE type="company"' cursor.execute(query) data = {} # Main node data. for (nid, title, status, created, changed, langcode) in cursor: data[nid] = { 'nid': nid, 'title': title, 'status': status, 'created': created, 'changed': changed,
def setUp(self): config = tests.get_mysql_config() self.cnx = connection.MySQLConnection(**config) self.drop_tables(self.cnx)
# Example to fetch selected Record Column wise from table using Like keyword # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # #Fetch Data from table using like keyword from mysql.connector import (connection) conn = connection.MySQLConnection(user='******', password='******', host='localhost', charset='utf8', database='testdb') sql_fetch = "SELECT RollNo FROM student WHERE RollNo Like '%cs%'" my_cursor = conn.cursor() my_result = my_cursor.fetchall( ) # This will fetch the records where the rollno contains the word "cs" for x in my_result: print(x)
def __init__(self): self.db_config = read_config_file() self.conn = connection.MySQLConnection(**self.db_config) self.curr = self.conn.cursor(cursor_class=MySQLCursorPrepared)
from mysql.connector import connection from datetime import datetime import sys qty = [1, 1000] neo4j_query = ['select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on b.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2', 'select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on a.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2', 'select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on b.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2 and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb2 and codigo_stringdb2 = c.codigo_stringdb2) IS NOT NULL', 'select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on b.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2 and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb1 and codigo_stringdb2 = c.codigo_stringdb2) IS NOT NULL', 'select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on b.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2 and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb1 and codigo_stringdb2 = c.codigo_stringdb1) IS NOT NULL and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb1 and codigo_stringdb2 = c.codigo_stringdb2) IS NOT NULL', 'select a.codigo_stringdb1, a.codigo_stringdb2, c.codigo_stringdb1, c.codigo_stringdb2 from Link a inner join Link b on a.codigo_stringdb2 = b.codigo_stringdb1 inner join Link c on b.codigo_stringdb2 = c.codigo_stringdb1 where a.codigo_stringdb1 != c.codigo_stringdb1 and a.codigo_stringdb1 != c.codigo_stringdb2 and b.codigo_stringdb1 != c.codigo_stringdb2 and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb1 and codigo_stringdb2 = c.codigo_stringdb1) IS NOT NULL and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb1 and codigo_stringdb2 = c.codigo_stringdb2) IS NOT NULL and (select codigo_stringdb1 from Link where codigo_stringdb1 = a.codigo_stringdb2 and codigo_stringdb2 = c.codigo_stringdb2) IS NOT NULL'] driver = connection.MySQLConnection(user='******', password='', host='127.0.0.1', database='Proteina') session = driver.cursor() for query in neo4j_query: for j in qty: time = [] print '%s - %s' % (query, j) for i in range(1, 11): start = datetime.now() queryrun = query + ' LIMIT %s, 1' % j; session.execute(queryrun) for record in session: print '%s %s' % (i, record['a.codigo_stringdb1']), sys.stdout.flush() time.append((datetime.now() - start).microseconds)
def setup_database(user: str, password: str, host: str, database: str): try: cnx = connection.MySQLConnection(user=user, password=password, host=host, database=database) except: print("Could not connect :(") sys.exit(1) cursor = cnx.cursor() print("Connected!!!") # Create a users table print("Creating Users Table") users_table = """ CREATE TABLE users ( userid int AUTO_INCREMENT PRIMARY KEY, username varchar(255) NOT NULL, password varchar(255) NOT NULL, s3bucket varchar(255) NOT NULL, s3key varchar(255) NOT NULL ); """ print(users_table) cursor.execute(users_table) # Add some users user = """ INSERT INTO users (username, password, s3bucket, s3key) VALUES (%s, %s, %s, %s); """ user1 = ("analyst1", "mypassword", "deside-cloud", "cases") user2 = ("analyst2", "somepassword", "deside-cloud", "cases") print(f'\nAdding User1') cursor.execute(user, user1) print(f'\nAdding User2') cursor.execute(user, user2) cnx.commit() # Create cases table (This will store metadata regarding users case) print("Creating Cases Table") case_table = """ CREATE TABLE cases ( case_id int AUTO_INCREMENT PRIMARY KEY, name varchar(255), description varchar(1024), s3bucket varchar(255), s3key varchar(255), owner varchar(255), datecreated datetime default current_timestamp, datemodfied datetime on update current_timestamp ); """ cursor.execute(case_table) # Create some cases case = """ INSERT INTO cases (name, description, s3bucket, s3key, owner) VALUES (%s, %s, %s, %s, %s); """ case1 = ("Circle Area", "Area of circle for customer x", "deside-cloud", "cases", "analyst1") case2 = ("Field Area", "Area of field for customer y", "deside-cloud", "cases", "analyst1") case3 = ("Triangle Area 2", "Area of triangular field for customer x", "deside-cloud", "cases", "analyst2") case4 = ("Circle Area", "Area of circular field for customer xx", "deside-cloud", "cases", "analyst2") case5 = ("Field Area 6", "Area of field for customer yy", "deside-cloud", "cases", "analyst2") print(f'\nCreating sample case1') cursor.execute(case, case1) print(f'\nCreating sample case2') cursor.execute(case, case2) print(f'\nCreating sample case3') cursor.execute(case, case3) print(f'\nCreating sample case4') cursor.execute(case, case4) print(f'\nCreating sample case5') cursor.execute(case, case5) cnx.commit() # # Setup the Methods table. Methods are stand alone programs that a user can add to a # case. The IDE will manage these # print("Creating methods table") method_table = """ CREATE TABLE methods ( method_id int AUTO_INCREMENT PRIMARY KEY, name varchar(255) NOT NULL, description varchar(1024) NOT NULL, s3bucket varchar(255) NOT NULL, s3key varchar(255) NOT NULL, owner varchar(255) NOT NULL, datecreated datetime default current_timestamp, datemodfied datetime on update current_timestamp ); """ cursor.execute(method_table) print("Done!") # Cleanup cursor.close() cnx.close()