ADODB Command failing Execute with parameterised SQL query - mysql

I have the following JScript code:
var conn = new ActiveXObject ("ADODB.Connection");
conn.Open("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=blah_blah_blah;User=foo;Password=bar;");
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE :search ORDER BY id";
var search = "test";
try{
cmd.CommandText = strSQL;
var param = cmd.CreateParameter(':search', 200, 1, 100, search);
cmd.Parameters.Append(param);
var rs = cmd.Execute();
}
catch (ex) {
Application.Alert("Error retrieving id information from database.");
}
I've verified (by printing them) that the Connection object is set to be the Command's ActiveConnection, the parameter object has the correct value and the Command object has the correct SQL query as its CommandText. I also inserted an alert statement after each line in the try block to see where the error was occuring - it's fine after cmd.Parameters.Append but the exception gets thrown upon running the Execute statement.
I've tried displaying the actual exception but it's just a generic 'Object error' message.
The query executes fine and returns the correct result set when I just execute the SQL query (without the parameter) straight through the Connection object, but seems to fail when I use a parameterised query with the Command object.
As far as I can see all settings and properties of the Command and Connection objects are correct but for whatever reason it's throwing an exception.
Any help with this would be much appreciated.

With ODBC and ADO, generally speaking, a question mark ? is used as the placeholder for parameters. Parameters are bound in the order they are appended to the Parameters collection to the placeholders in the command. In your example, replace strSQL with:
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE ? ORDER BY id";
You can still name the parameter that you create, but the only purpose it would serve is to be able to reference it by name later (e.g., with cmd.Parameters.Item(":search")).

Related

Error when using textbox values inside string sql

"Select item from table1 where Spare parts='"+ textbox1.text+"'".
I have tried to replace item with Textbox2.text.
I used :
"Select'"& textbox2.text& "' from table1 where Spare parts='"+ textbox1.text+"'"
I got error.
I used "+ textbox2.text+" I got error too
What you have here is one of the fastest ways out there to get your app hacked. It is NOT how you include user input in an SQL statement.
To explain the right way, I also need to include the connection and command objects for context, so I may also have a different pattern for how I handle these than you're use to. I'm also assuming the mysql tag in the question is accurate (though I have my doubts), such that the correct code looks more like this:
string SQL = "Select item from table1 where `Spare parts`= #SpareParts";
using cn = new MySqlConnection("connection string here")
using cmd = new MySqlCommand(SQL, cn)
{
cmd.Parameters.AddWithValue("#SpareParts", TextBox1.Text);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// ...
}
}
}
Note the backticks around Spare Parts, so it will be correctly treated as a single object name by MySql.

Parameterized upsert command over odbc doesn´t work

i have a problem with doing parameterized upsert commands over odbc.
Thats the upsert command
Dim upsert As New OdbcCommand
upsert.Connection = connection
upsert.CommandText = "
INSERT INTO products_replacement
(products_model, products_replacement)
VALUES
(#products_model, #products_replacement)
ON DUPLICATE KEY UPDATE products_replacement = #products_replacement;
"
upsert.Parameters.Add("#products_replacement", OdbcType.VarChar)
upsert.Parameters.Add("#products_model", OdbcType.VarChar)
For Each Product In ListOfProducts
upsert.Parameters.Item("#products_replacement").Value = Product.Value
upsert.Parameters.Item("#products_model").Value = Product.Key
upsert.ExecuteNonQuery()
NEXT
Error message: "ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.7.30]Column 'products_model' cannot be null"
In the Debugger the values of the parameters are correctly set.
Something like that works
upsert.Commandtext = upsert.Commandtext.Replace("#products_replacement", $"'{Product.Value}'").Replace("#products_model", $"'{Product.Key}'")
upsert.ExecuteNonQuery()
ListOfProducts is a Dictionary(Of String, String)
Error handling and other stuff is stripped from my above example code.
Parameterized querys are prefered and i had no problems doing the same with MS SQL...
What am I missing?
Help is appreciated.
ODBC doesn't use named parameters
You can give them names in the SQL, but you should then imagine that they all get transformed into ? and are treated positionally by the driver; the name is meaningless
This means you need to add as many parameters to your VB Command.Parameters collection as your statement contains, even if it means repeating values - you cannot reuse VB parameters them by repeating the name in the SQL. The name is still semi useful in VB for indexing purposes:
Dim upsert As New OdbcCommand
upsert.Connection = connection
upsert.CommandText = "
INSERT INTO products_replacement
(products_model, products_replacement)
VALUES
(?, ?)
ON DUPLICATE KEY UPDATE products_replacement = ?;
"
upsert.Parameters.Add("#pmod", OdbcType.VarChar)
upsert.Parameters.Add("#prep1", OdbcType.VarChar)
upsert.Parameters.Add("#prep2", OdbcType.VarChar)
For Each Product In ListOfProducts
upsert.Parameters.Item("#pmod").Value = Product.Value
upsert.Parameters.Item("#prep1").Value = Product.Key
upsert.Parameters.Item("#prep2").Value = Product.Key
upsert.ExecuteNonQuery()
NEXT

Microsoft Jet OLEDB syntax error on UPDATE

I have a database similar to the one below:
Table1(AutoNumber, Text, Number, Memo) // this is field types
Table1(ID, Title, Price, Image)
I'm trying to update an existing element of the database in C# using:
const string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=bd.mdb";
OleDbConnection m_dataBase = new OleDbConnection(connectionString);
OleDbConnection m_dataBase.Open();
SQL = "UPDATE Table1 SET Title='test', Price=35, Image='Test' WHERE ID=1";
OleDbCommand SQLQueryCommand = new OleDbCommand(SQL, m_dataBase);
int response = SQLQueryCommand.ExecuteNonQuery();
As a result I am getting this error. "Microsoft JET Database Engine Error syntax in UPDATE instruction".
What am I doing wrong?
PS: I can successfully do SELECT or INSERT, but not UPDATE.
Well, if your SQL command is the only problem, there are some visible issues.
Simply try to parametrize your Update clause using such as below which will prevent lots of little mistakes and also an SQL injection.
SQL = "UPDATE Table1 SET Title=?, Price=?, Image=? WHERE ID=?";
SQLQueryCommand.Parameter.Add("#MyTitle", OleDbType.VarChar).Value = "Test";
SQLQueryCommand.Parameter.Add("#MyPrice", OleDbType.Integer).Value = 35;
SQLQueryCommand.Parameter.Add("#MyImage", OleDbType.VarChar).Value = "TestAgain";
SQLQueryCommand.Parameter.Add("#MyID", OleDbType.VarChar).Value = 1;
To learn more about parametrization try having a look at the example in the bottom of this MSDN article.
OleDbCommand.Parameters Property
Also, it's a good practice to surround your connection inside a using statement.
using (var m_dataBase = new OleDbConnection(connectionString) { ... }

How can I display data into my Jtextarea from my data base Mysql

I have problem when I try to display data(the result of a query) from my database mysql to my jTextarea, when I compile I have an error exception like:
SQL Exception: java.sql.SQLException: Can not issue SELECT via executeUpdate()
I have used a "select" query from my table where the name is the name written in my jTextFieldNom,this is my code, I hope that some one help me because I don't know how to resolve the problem, I 'm sure that my query is correct but I don't know where is the problem.
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
instruction = connexion.createStatement();
int rowsEffected = instruction.executeUpdate(SQL);
jTextArea1.append(rs.getString("description"));
}
...... //bloc catch
This line is executing a Select statement which is throwing the error.
int rowsEffected = instruction.executeUpdate(SQL);
You don't need this line because you aren't updating your database.
Also change the append to setText
jTextArea1.setText(rs.getString("description"));
Try this:
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
jTextArea1.setText(rs.getString("description"));
}

Connection Manager in Script Component

How will we use Connection Manager in Script component, using OLEDB Provider ? I had tried using Connection Manager with OLEDB Provider and SQL, but failed. what is the correct way to use ?
The syntax is different between a Script Task and a Script Component. Check out this article for more than a couple side-by-side comparisons:
http://msdn.microsoft.com/en-us/library/ms136031.aspx
This is well documented on MSDN, covering both VB and C# type of scripts: http://msdn.microsoft.com/en-us/library/ms136018.aspx
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
DataTable dtExcelData = new DataTable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();