insert value textbox into mysql database - c#

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)

Related

Insert to MySql from c# failed

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.

SQL Syntax error in C# string

I'm running a query from a web form to update records. Since I'm just learning about C#, I'm using a command string as opposed to a stored procedure.
My update method is as follows:
public void updateOne()
{
string commandText = "update INVOICE SET <Redacted> = #<Redacted>,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
<needed a line break here, which is why I split the string again>
+ "WHERE K_INVOICE = #K_INV";
using (SqlConnection dbConnection = new SqlConnection
(conParams.connectionString))
{
SqlCommand cmd = new SqlCommand(commandText, dbConnection);
cmd.Parameters.Add("#K_INV", SqlDbType.Int);
cmd.Parameters["#K_INV"].Value = #K_INV;
cmd.Parameters.AddWithValue("#<Redacted>", #<Redacted>.ToString());
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
cmd.Parameters.AddWithValue("#SupN", #SupN.ToString());
cmd.Parameters.AddWithValue("#Net", #Net.ToString());
cmd.Parameters.AddWithValue("VAT", #VAT.ToString());
cmd.Parameters.AddWithValue("#InvDt", #InvDt.ToString());
try
{
dbConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
errorString = e.Message.ToString();
}
}
}
Catch stalls on an SQL error (Incorrect syntax near SET), and I have an idea that the issue occurs because I convert the parameters to strings. The first parameter is an Int, which should be OK.
If this is the case, what should I convert the parameters to? If not, what on earth is wrong?
Try to add a # before the string to escape the breaklines, for sample:
string commandText = #"update INVOICE SET [Redacted] = #Redacted,
Supplier = #Sup, SupplierName = #SupN, NetTotal = #Net,
VATTotal = #VAT, InvoiceDate = #InvDt "
+ "WHERE K_INVOICE = #K_INV";
In parameterName argument you can add the # but the value not, just the variable, for sample
cmd.Parameters.AddWithValue("#Redacted", redacted.ToString());
Try to execute this query in the databse with some values to check if everything is correct. You could use [brackets] in the table name and column names if you have a reserved word.
I would recommend you read this blog article on the dangers of .AddWithValue():
Can we stop using AddWithValue already?
Instead of
cmd.Parameters.AddWithValue("#Sup", #Sup.ToString());
you should use
cmd.Parameters.Add("#Sup", SqlDbType.VarChar, 50).Value = ...(provide value here)..;
(is your variable in C# really called #SupN ?? Rather unusual and confusing....)
I would recommend to always define an explicit length for any string parameters you define

Debug "Syntax error in INSERT INTO statement" in C# when submitting data to Access Database using OleDbConnection

I'm diving head first into both C# and Access databases. This is all brand new to me, so I have a small test database set up to work with a small template. I'm trying to figure out why I keep getting a syntax error that is triggered by the ExecuteNonQuery() method. Any help and insight would be appreciated.
Edit: SOLVED: This is the working code for this situation. All help was greatly appreciated!
public void addToDb()
{
String first = "John";
String last = "Doe";
String testPath = GVar.TEST_FILEPATH + GVar.TEST_DATABASE;
String strCommand = "INSERT INTO ID ([First], [Last]) Values(#First, #Last)";
OleDbConnection dbTest = null;
OleDbCommand cmd = null;
try
{
dbTest = new OleDbConnection(GVar.OLE_DB_WRITE + testPath);
dbTest.Open();
cmd = new OleDbCommand(strCommand, dbTest);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
Console.WriteLine("Data Added");
}
catch (Exception ex)
{
Console.WriteLine("Db Test: " + ex.Message);
}
dbTest.Close();
}
From OleDbCommand.Parameters property
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.
I don't see anything wrong in your INSERT statement other than this.
cmd.CommandText = "INSERT INTO Identity ([First],[Last]) VALUES(?, ?)";
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();

Insert error in postgresql DB with c#

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);

How to insert an integer into a database through command prompt

I am trying to insert a integer into a database in C# using the code below, but everytime I run the compiler informs me that my integer is not a valid column "Invalid Column Name UserID"
Does anyone have any insight on this? Thanks.
Console.WriteLine("Please enter a new User Id");
string line = Console.ReadLine();
int UserID;
if (int.TryParse(line, out UserID))
{
Console.WriteLine(UserID);
Console.ReadLine();
}
//Prepare the command string
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES (UserID,'Ted','Turner')";
First things first, I would get into the habit of using parameterised queries, if you are not planning to use stored procedures. In your example, I would:
using (var command = new SqlCommand("INSERT INTO tb_User(ID, f_Name, l_Name) VALUES (#id, #forename, #surname)", conn))
{
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("forename", forename);
command.Parameters.AddWithValue("surname", surname);
command.ExecuteNonQuery();
}
Where id, forename, surname are the appropriate variables. Notice I am also using using blocks, this ensures that my objects are cleaned up after it has completed.
it is because the 'UserID' within your insertString : ..."VALUES (UserID"... is invalid.
you need to pass a value for the UserID such as: ..."VALUES ('myUserIDGoesHere'"...
Your string is not dynamically reading the variables. Use something like this:
string insertString =
string.Format(#"INSERT INTO
tb_User(ID,f_Name, l_Name) VALUES
({0},'{1}','{2}')", UserId, "Ted",
"Turner");
There are better ways depending on what kind of data access you're using, but this is just to make the point of how to correct the string.
The problem is the first argument in VALUES - it simply isn't defined. If this is meant to be the value the user has entered, then you need to add a parameter to the command and use that parameter in the SQL; for example:
cmd.Parameters.AddWithValue("#id", UserID);
An then use
VALUES(#id, ...
in the TSQL.
Also, generally you might want to have the system generate the unique id. A the simplest level this could have an IDENTITY defined (an automatic sequence).
Use a parameterized query:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var insertCommand = new SqlCommand(
#"INSERT INTO tb_User (ID, f_Name, l_Name)
VALUES (#ID, 'Ted', 'Turner')", connection))
{
insertCommand.Parameters.AddWithValue("#ID", userID);
insertCommand.ExecuteNonQuery();
}
}
To answer your question regardless of your approach, try:
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES ("
+ UserID + ",'Ted','Turner')";

Categories