Matlab Database QueryDb error - mysql

I need to insert some data into a mysql database. Db is connected and working.
I am running the following code :
a = sprintf('%s',hashedStr);
sqlQueryStr = 'insert into products (security_code) values (a)'
QueryDB(sqlQueryStr);
I have a database called test and a table named products with 2 fields id and security_code.
When I run this, I get :
Unknown column 'a' in fieldlist ...
Why is this happening ? i dont have and dont need this column ...
Any help ?

Try with:
sqlQueryStr = sprintf('insert into products (security_code) values ("%s")',hashedStr);
QueryDB(sqlQueryStr);
problem is that you are not replacing "a" variable into sql expression

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 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.

updating in razor webmarix

Line 22: var sql3 = "UPDATE productori SET Name3=#0, detail2=#1, harga2=#2 WHERE id=#3";
Line 23: var db2 = Database.Open("SmallBakery");<br>
Line 24: **db2.Execute(sql3 ,Name3, detail2, harga2);**
The bold area showing where the error is.
I have a problem with updating my database. I'm new with webmatrix and razor.
`Exception Details: System.Data.SqlServerCe.SqlCeException: The column name is not valid. [ Node name (if any) = ,Column name = Name3 ]`
That is the error that I get.
Below is my database format:
`ID = identity=big int
Name nvarchar
Description nvarchar
price nvarchar`
Help me understand what I did wrong please.
There is no column called Name3 in your database, but your SQL attempts to reference one with that name. Change the SQL so that the column names match what you have in the database. Also, you have 4 parameter markers in your SQL, but you only provide values for 3 of them so your SQL will never update any records.
Your SQL should look like this:
"UPDATE productori SET Name=#0, Description=#1, Price=#2 WHERE ID=#3";
Then you need to pass a value for the ID:
db2.Execute(sql3, Name3, detail2, harga2, variable_containing_id_value);

MYSQL Error:1054 - Unknown Column

just having some trouble with an SQL update in PHP. Listed below is an extract of the function:
$captain = $this->getUserName();
$member = $textParts[1];
$memberNo = 'member1';
$sqlUpdate = 'UPDATE ajax_chat_draft_teams SET '.$memberNo.'='.$member.' WHERE captain='.$captain.'';
$result = $this->db->sqlQuery($sqlUpdate);
When the Query is reached it throws the following error:
Query: UPDATE ajax_chat_draft_teams SET member1=user WHERE captain=Oolius
Error-Report: Unknown column 'Oolius' in 'where clause'
Error-Code: 1054 error occured!
The table ajax_chat_draft_teams has 5 fields: captain, member1, member2, member3, member4
(Note: There is a record in the table where the captain is Oolius and all members are NULL).
I'm failing to see what is wrong with my SQL statement. Thanks for your time.
Try this:
$sqlUpdate = 'UPDATE ajax_chat_draft_teams SET '.$memberNo.' = "'.$member.'" WHERE captain = "'.$captain.'"';
String literals need to be surrounded in single quotes. The query should look like this:
UPDATE ajax_chat_draft_teams SET member1='user' WHERE captain = 'Oolius'
Also, consider using PDO and bind variables.
You need to put Oolius in quotes other MySQL thinks it is a column name.
Use this
$sqlUpdate = 'UPDATE ajax_chat_draft_teams SET
'.$memberNo.'="'.$member.'" WHERE captain="'.$captain.'"';
i hope it will help you.

Error while inserting perl variable in the mysql table on html page

Error while inserting email address in the table
**[perl] my $username=$CGI->{salesrep}; return $username;[/perl]#gmail.com**
I want to insert this value in the table.
But It gives null when executed.
[query type=list sql="INSERT tech4less.outofstock_sku SET name='[value name]',customer_email='[value email]', phone='[value phone]', state='[value b_state]', postalcode='[value zip]', country='[value country]', **salesperson='[perl]$username[/perl]#gmail.com**', product='[value wish_product]', item_description='[value wish_descrip]', manufacturer='[value wish_man]', category = '[value wish_cat]', business_yn='[value option]', date = now()"]
[/query]
If $CGI is a CGI object then access a parammeter this way:
my $username=$CGI->param('salesrep');
Read this: http://perldoc.perl.org/CGI.html#FETCHING-THE-VALUE-OR-VALUES-OF-A-SINGLE-NAMED-PARAMETER:
Regards