I have a problem with a MySql insert ... this is my Code:
public class struc
{
public string Product;
public string Underproduct;
public string Version;
}
static void DatabaseConection(List<struc> Data)
{
string connString = "right connection info";
string insertQuery = "Insert into freigabedaten (produktname,unterprodukt,version,freigabestatus) values (productInfo.Product,productInfo.Underproduct,productInfo.Version,'4')";
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
foreach (var productInfo in Data)
{
MySql.Data.MySqlClient.MySqlCommand Command = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, conn);
try
{
Command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
});
conn.Close();
}
But i get always the Exeption:
MySql.Data.MySqlClient.MySqlException: "Unknown column
'productInfo.Product' in 'field list'"
My Database table structure is:
Databasetablescreen
can someone help me please?
Seems that you're passing all INSERT query arguments as part of query string, not as reference to productInfo object which contains column names (which they're treated as table names instead).
Use a parameterized MySQL query like this:
string insertQuery = "Insert into freigabedaten (produktname,unterprodukt,version,freigabestatus) values (#produktname,#underprodukt,#version,'4')";
And then declare input parameters for MySqlCommand inside foreach loop before using ExecuteNonQuery method:
MySql.Data.MySqlClient.MySqlCommand Command = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, conn);
Command.Parameters.AddWithValue("#produktname", productInfo.Product);
Command.Parameters.AddWithValue("#unterprodukt", productInfo.Underproduct);
Command.Parameters.AddWithValue("#version", productInfo.Version);
Command.ExecuteNonQuery();
What are you trying to do?
If productInfo is a C# Struct/Class you need to add the values manually to the Query string.
string insertQuery = "Insert into freigabedaten (produktname,unterprodukt,version,freigabestatus) values ('"+productInfo.Product+"','"+productInfo.Underproduct+"','"+productInfo.Version+"','4')";
If productInfo is another table you'll need to query these values beforehand.
Related
I'm trying to Insert multiple records to table using ado.net, and print id inserted.
My code is like this:
List<string> listQuery = new List<string>()
{
"INSERT INTO Students (Name) VALUES ('student1');SELECT ##Identity;",
"INSERT INTO Students (Name) VALUES ('student2');SELECT ##Identity;",
"INSERT INTO Students (Name) VALUES ('student3');SELECT ##Identity;",
};
using (SqlConnection connection = new SqlConnection(_connectionString))
{
try
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
foreach (var myQuery in listQuery)
{
command.CommandText = myQuery;
int id = Convert.ToInt32((decimal)command.ExecuteScalar());
Console.WriteLine("Inserted: " + id);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//Close and dispose
connection.Close();
}
}
I wondering, whether should I execute every command like that? Or concatenate all query and execute just a times?.
If I should execute one times. How can i get all id of records inserted?
you can use the OUTPUT clause to return the identity id
INSERT INTO Students (Name)
OUTPUT INSERTED.id
VALUES ('student1'), ('student2'), ('student3');
Don't go like this, and DON'T call database in ANY loop.
For resolving your problem, you should write stored procedure that take a DataTable as input of your student list (tutorial) or use JSON string as input. In that stored procedure you use OUTPUT clause to retrieve id: OUTPUT INSERTED.id . On C# code, you only need ExecuteReader to get all id.
I get an error when I try to run this method:
public bool InsertLog(string logMsg, string type)
{
bool result = false;
string sql = "INSERT INTO `log`(`logmsg`, `type`) VALUES (?a, ?b)";
using (SQLiteConnection conn = new SQLiteConnection(m_dbConnectionString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandText = sql;
comm.Parameters.AddWithValue("?a", logMsg);
comm.Parameters.AddWithValue("?b", type);
int res = comm.ExecuteNonQuery();
result = (res == 1);
}
conn.Close();
}
return result;
}
On this database table:
CREATE TABLE log (
id INTEGER PRIMARY KEY,
createdAt DATETIME DEFAULT (datetime('now', 'localtime') ),
logmsg TEXT,
type VARCHAR
);
The error message is {"SQL logic error or missing database\r\nnear \"a\": syntax error"} (System.Data.SQLite.SQLiteExpcetion). Where is the syntax error in the insert query? I don't see it. Can't I use prepared statements this way?
Quotation marks in values (?, ?) are for positional parameters, so ?a is incorrect (you can, however, use something like ?123). If you want to use named parameters, change that to #a.
See Binding Values To Prepared Statements.
private void button1_Click(object sender, EventArgs e)
{
string tablename = label2.Text;
string name = TextBox1.Text;
DBconnection.savetodb(tablename, name);
}
I call the method below from another form to save the name into a specific table. But it wont save into my table in database.
public static void savetodb(string tablename, string name)
{
OleDbConnection connection = GetConnection();
string query = String.Format("INSERT INTO {0} (Name) VALUES (#Name)", tablename);
OleDbCommand cmd = new OleDbCommand(query, connection);
cmd.Parameters.AddWithValue("#Name", name);
try{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex){
Console.WriteLine("Exception catch", ex);
}
finally{
myConnection.Close();
}
Thanks for help.
You are not passing table name as a parameter, you are passing your #Name value as a parameter. You can't pass a table name as a parameter even if you want. Parameters only for values, not table or column names. You are just formatting your query based table name. As far as I see, your problem using named parameters. OleDb provider does not support named parameters.
From OleDbCommand.Parameters
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Try it as;
string query = String.Format("INSERT INTO {0} (Name) VALUES (?)", tablename);
...
cmd.Parameters.AddWithValue("#name", name);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection connection = new GetConnection())
using(OleDbCommand cmd = con.CreateCommand())
{
}
And consider to use .Add method instead .AddWithValue. It may cause some problems. Read Can we stop using AddWithValue() already?
I want to insert the String ' xxx'xxx ' in a field of a Table. The problem in the ' character.
How i can insert this character?
You need to duplicate the single quote:
insert into foo (col_name)
values
('xxx''xxx');
But you should look into prepared statements which will not only make things like that a lot easier but will also protect you from SQL injection (I don't know C#, so I can't help you with the details).
double the single quote if you are inserting directly,
INSERT INTO tableName (colName) VALUES ('xxx''xxx')
but if you are doing it on C#, use parameterized query.
string connStr = "connection String here";
string val = "xxx'xxx";
string query = "INSERT INTO tableName (colName) VALUES (:val)";
using(NpgsqlConnection conn = new NpgsqlConnection(connStr))
{
using(NpgsqlCommand comm = new NpgsqlCommand())
{
comm.Connection = conn;
comm.CommandText = query;
NpgsqlParameter p = new NpgsqlParameter("val", NpgsqlDbType.Text);
p.value = val;
comm.Parameters.Add(p);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(NpgsqlException e)
{
// do something with
// e.ToString();
}
}
}
PostgreSQL and C# - Working with Result Sets - Npgsql .NET Data Provider
In c# If you want to insert single quote you can do this by replacing original value so:
string x = "xxx'xxx";
string replacedText = x.Replace("'","''");
and when inserting to prevent from sql injection always use Parameters:
myCommand.CommandText = "INSERT INTO TableName (x) VALUES (#x)";
myCommand.Parameters.Add("#x", x);
I have problems inserting a textboxvalue into a mysql database - there's no errormessage and no inserting. What am I doing wrong
private void RegisterCustomer()
{
string firstname = txtfirstname.ToString();
OdbcConnection conn;
conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["jConnString"].ConnectionString);
conn.Open();
string sql = "insert into klant (firstname) values (#firstname)";
OdbcCommand cmd = new OdbcCommand(sql, conn);
cmd.Parameters.Add("#firstname", OdbcType.VarChar).Value = firstname;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Check.Text += ex.ToString() + sql;
}
finally
{
conn.Close();
conn.Dispose();
Check.Text += "OK";
}
}
According to MSDN.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbccommand.parameters.aspx
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder.
So your query should be:
string sql = "insert into klant (firstname) values (?)"
If you have multiple parameters, they are set in the order you add them.
In addition, I think the line
string firstname = txtfirstname.ToString();
should read
string firstname = txtfirstname.Text();
But that is not what is causing your immediate problem.
"insert into klant values (firstname) values (#firstname)"
I think the right query would be:
"insert into klant values (#firstname)";
Your query:
string sql = "insert into klant values (firstname) values (#firstname)";
Is specifying values twice. It should be in the form:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
So remove the extra values and you should be good.
You have values twice. I've never seen it that way. You INSERT INTO table (columm_names...) VALUES (value1, 'value2',...)
edit: maybe you should try straight text and eliminate the box to see if it enters. At least you'll know where to look.
edit: I'd also echo my firstname variable to see what it has.
More accurately, it should be:
insert into klant (firstname) values (#firstname)