MySQL query in R to compare with certain value [duplicate] - mysql

This question already has answers here:
Pass string variable in R script to use it in SQL statement
(4 answers)
Closed 6 years ago.
args <- commandArgs(trailingOnly = TRUE)
id = as.character(args)
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'manu',host = 'localhost')
sql<-sprintf("select * from net where ips1=%s;",id)
up = dbGetQuery(mysqlconnection, sql)
I am trying to retrieve records from the table net using R.
I want to retrieve the records with a specific id which is being passed as a command line argument.However i am getting an error near " ips1=%s ",saying that the SQL syntax which i used is incorrect. Any help?

Please, try to enclose the string value to compare in single quotes ':
sql <- sprintf("select * from net where ips1='%s';",id)

Related

How to insert data into a table containing one single column?

I'm currently learning Python and MySQL and have an issue inserting data if my table has one single column (actually one auto-incremented id and a column).
I tried several syntaxes, "playing" with quotes and parenthesis, several ways to implement execute() method, but nothing worked.
Here is my statement :
import mysql.connector
db_name = "purbeurre"
list_categories = ['Drinks', 'Meat', 'Bread']
cnx = mysql.connector.connect(user='toto', password='toto', host='123.456.0.78')
cursor = cnx.cursor()
cursor.execute("USE {}".format(db_name))
insert_categories = ("INSERT INTO Categories (name) VALUES (%s)")
cursor.executemany(insert_categories, list_categories)
The error is : "ValueError: Could not process parameters"
If I add a column, the statement becomes this one and works fine :
import mysql.connector
db_name = "purbeurre"
list_categories = [('Drinks', 'Liquid products'), ('Meat', 'All kind of meat', ('Bread', 'Bakery products')]
cnx = mysql.connector.connect(user='toto', password='toto', host='123.456.0.78')
cursor = cnx.cursor()
cursor.execute("USE {}".format(db_name))
insert_categories = ("INSERT INTO Categories (name, description) VALUES (%s)")
cursor.executemany(insert_categories, list_categories)
As you can see, the only difference is the number of columns.
Any idea of what happens?
I received the answer.
The list of data was not correctly defined, here is the correct syntax :
list_categories = [('Drinks',), ('Meat',), ('Bread',)]
Beware of the comma before the parenthesis is closed to ensure each element in the list are tuples.

MySQL query returning false, but executing correctly [duplicate]

This question already has answers here:
Inserting preparedstatement to database - PSQL
(1 answer)
how to get true or false using execute() in Java Statement [duplicate]
(5 answers)
Closed 4 years ago.
I am working out of Google Apps Script and connecting to an external database using JDBC.
I have a user table and a contracts table, I have changed some of the values for privacy but this is my basic query. Basically I have a list of contract numbers that I want to loop over, and for each one, execute the query. The contracts table and the user table share a primary id, so I am just trying to update a value in the user table, where the users contract id equals the contract id of that contract number.
var contractNumbers = ["123","456","789"];
for (var a in contractNumbers) {
var stmt = conn.createStatement();
var contractNum = contractNumbers[a];
var query = "UPDATE user INNER JOIN contracts ON user.id_c = contracts.id SET user.quantity = '1' WHERE contracts.number = '" + contractNum + "'";
var stmt = conn.prepareStatement(query);
var result = stmt.execute();
}
This query is working and is changing the value correctly and accurately, however the result always returns false. Any idea what may be wrong with my query that it is working, but returning false? Or maybe a suggestion for a better way to execute this query?
As you are entering datas and not getting datas the return is false
The doc says:
Returns:
true if the first result is a ResultSet object; false if the first result is an update count or there is no result.
In your case it's an update and there is no result
Full documentation here
Thanks to #JSmith above, I was pointed in the right direction. The proper execution is:
var result = stmt.executeUpdate(query);
Per - Cannot issue data manipulation statements with executeQuery()

Retrieving a key value from WTForms SelectField using Flask [duplicate]

This question already has an answer here:
Python sqlite3 parameterized drop table
(1 answer)
Closed 5 years ago.
I am having a problem with WTForms in Flask, I want to create a add_menu function which adds menu to the database. User can choose from SelectField "Appetizer", "Main Dish", or "Drinks" accordingly. So whenever user chooses the value from SelectField it adds to the corresponding table in a database. (I use MySQL). For some reason when I use menu_type = form.menu_type.data it gives me the following error
mysql_exceptions.ProgrammingError: (1064, "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 ''main_dishes'(name,ingredients,price) VALUES('Salmon', 'duude,frv', '35')' at line 1")
It takes the right value, but I have this awkward '' signs infront of main_dishes string
My code looks as follows:
class MenuForm(Form):
menu_type = SelectField('Menu Type', [validators.DataRequired()], choices=[('appetizers','Appetizer'),('main_dishes','Main Dish'),('desserts','Dessert'),('drinks','Drinks')], coerce=str)
name = StringField('Name', [validators.Length(min=1, max=2000)])
ingredients = TextAreaField('Ingredients', [validators.Length(min=10)])
price = DecimalField('Price (Manat)', [validators.DataRequired()])
#app.route('/add_menu', methods=['GET','POST'])
#is_logged_in
def add_menu():
form = MenuForm(request.form)
if request.method == 'POST' and form.validate():
menu_type = form.menu_type.data # <---Here is the problem
name = form.name.data
ingredients = form.ingredients.data
price = form.price.data
#Create cursor
cur = mysql.connection.cursor()
#execute
cur.execute("INSERT INTO %s(name,ingredients,price) VALUES(%s, %s, %s)", (menu_type,name,ingredients,price))
#Commit to DB
mysql.connection.commit()
#CLose connection
cur.close()
flash('Menu is Added', 'success')
return redirect(url_for('dashboard'))
return render_template('add_menu.html', form=form)
The table name is substituted as a quoted string and the query executed as such.
You may want to build your query with the table name before binding parameterized values.
query = "INSERT INTO {}(name,ingredients,price) VALUES(%s, %s, %s)".format(menu_type)
cur.execute(query, (name,ingredients,price))

How to create MySQL database programmatically using matlab

I am doing some data analytics using MySQL and Matlab. My program works fine if there is already an existing database present. But it doesn't work when there is not database for which I am trying to create connection. Now, what I want to do is to create a database with a fixed name if there is no database present in that name. I searched all over the internet and haven't found any option for that. May be I am missing something.
Additionally, I would like to create a table on the newly created database and store some random data on them. I can do this part. But I am stucked on the first part which is creating database programmatically using matlab.
Please note that, I have to use only matlab for this project. Any kind cooperation will be greatly appreciated.
Update
The code example is given below -
%findIfFeederExists Summary of this function goes here
% finds whether there is no. of feeders are empty or not
% Detailed explanation goes here
%Set preferences with setdbprefs.
setdbprefs('DataReturnFormat', 'dataset');
setdbprefs('NullNumberRead', 'NaN');
setdbprefs('NullStringRead', 'null');
%Make connection to database. Note that the password has been omitted.
%Using ODBC driver.
conn = database('wisedb', 'root', '');
conn.Message;
%Read data from database.
sqlQuery = 'SELECT * FROM joined_table';
%sqlQuery = 'SELECT * FROM joined_table where joined_table.`N. of Feeder` > 0';
curs = exec(conn, sqlQuery);
curs = fetch(curs);
dbMatrix = curs.data;
[row_count, ~] = size(dbMatrix);
if (row_count >= id)
val = dbMatrix(id, 3);
disp(val);
if (val.N0x2EOfFeeder > 0)
Str = strcat('Feeder is present on the id : ', num2str(id));
disp(Str);
disp(dbMatrix(id, 1:end));
else
Str = strcat('Feeder is NOT present on the id : ', num2str(id));
disp(Str);
end
else
Str = strcat('No row found for id : ', num2str(id));
disp(Str);
end
% = exec(conn,'SELECT * FROM inventoryTable');
close(curs);
%Assign data to output variable
%Close database connection.
close(conn);
%Clear variables
clear curs conn
end
You can see I can connect to an existing database using ODBC. But I am not sure how I can create a new database. What can be done for this?

MySQL Dynamic Query Statement in Python with Dictionary

Very similar to this question MySQL Dynamic Query Statement in Python
However what I am looking to do instead of two lists is to use a dictionary
Let's say i have this dictionary
instance_insert = {
# sql column variable value
'instance_id' : 'instnace.id',
'customer_id' : 'customer.id',
'os' : 'instance.platform',
}
And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.
Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.
sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)
Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary
Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at http://mail.python.org/pipermail/tutor/2010-December/080701.html. Relevant part:
Here's what I came up with when I tried to make a generalized version
of the above:
def add_row(cursor, tablename, rowdict):
# XXX tablename not sanitized
# XXX test for allowed keys is case-sensitive
# filter out keys that are not column names
cursor.execute("describe %s" % tablename)
allowed_keys = set(row[0] for row in cursor.fetchall())
keys = allowed_keys.intersection(rowdict)
if len(rowdict) > len(keys):
unknown_keys = set(rowdict) - allowed_keys
print >> sys.stderr, "skipping keys:", ", ".join(unknown_keys)
columns = ", ".join(keys)
values_template = ", ".join(["%s"] * len(keys))
sql = "insert into %s (%s) values (%s)" % (
tablename, columns, values_template)
values = tuple(rowdict[key] for key in keys)
cursor.execute(sql, values)
filename = ...
tablename = ...
db = MySQLdb.connect(...)
cursor = db.cursor()
with open(filename) as instream:
row = json.load(instream)
add_row(cursor, tablename, row)
Peter
If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for returning a dictionary of values, but it can't execute from a dict.