I am trying to insert two values to mysql database through two textboxes using WPF and C#. I am connecting to the database successfuly but when I try to insert the data I get error: Column "user_name" can not be null. What is really confusing be is that I am entering data in the first and the second textboxes. It seems that the data to inserted in the textboxes is not passed. My question is do you know where is the problem and how to fix it?
PS: my database is very simple contain id as int16 auto incremented, name as varchar100 and user_password as varchar100
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("Insert into niki2 values (#id,#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
Guys after I did couple of changes I am getting this error message:
Unknown column 'name' in 'field list'
Here is edited code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
When I replace name with user_name and try to insert data I get an error ** Column "user_name" cannot be null**
The affected line is :
da.InsertCommand.ExecuteNonQuery();
Do you have any idea how to solve it?
Look at your code:
da.InsertCommand.Parameters.Add("#user_id", MySqlDbType.Int16).Value = "";
da.InsertCommand.Parameters.Add("#user_name", MySqlDbType.VarChar).Value = "";
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value =
textBox2.Text;
Now look at what you've said:
It seems that the data to inserted in the textboxes is not passed.
Look at the code again. Look at the value being used for user_name (and indeed user_id). How is that using a textbox value? How are you expecting the data from textBox1 to get to the database when your code never mentions it?
Additionally, as sblom mentions in comments, I'd encourage you to use explicit column names - at which point you won't need to specify anything for user_id, which I assume is an auto-generated identity column anyway. (It therefore doesn't make sense to try to insert an empty value into it.) It's not clear why you're trying to use an empty string as a value for an Int16 column, either...
EDIT: For your edited code:
da.InsertCommand = new MySqlCommand(
"INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
Given your first error, the column is user_name, not name...
Can you just check what table you want to use exactly?
in your actual question it was
da.InsertCommand = new MySqlCommand("Insert into **niki2** values (#id,#name, #user_password)", con);
and in updated question the table name is changed to
da.InsertCommand = new MySqlCommand("INSERT INTO **niki** (name, user_password) VALUES (#name, #user_password)", con);
I feel you have two tables you are playing with and are confused
seems like
name is in niki2 and
user_name is in niki probably your actual table.
I am sure no one can answer with this much ambiguity
Try
For Table niki
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_name, user_password) VALUES (#user_name, #user_password)", con);
For Table niki2
da.InsertCommand = new MySqlCommand("INSERT INTO niki2 (name, user_password) VALUES (#name, #user_password)", con);
OR Reversal
Luck
You haven't specified in the insert statement in which fields the values should be stored, so the values will end up in the first three fields in the order that you specified, regardless of their names. I guess that the user name field is the fourth, so it doesn't get a value, thus being null.
Specify which fields should be used:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_id, user_name, user_password) VALUES (#user_id,#user_name, #user_password)", con);
finally I find the problem causing me this exception. As you can see my old code:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
What I did was to replace the
# with ?
And basically my code looked like :
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (?name, ?user_password)", con);
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("?user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
Thanks to all who involved in the discussion!
Related
I'm developing an ASP.NET MVC Web Application using SQL Server.
I am trying to INSERT a new entry into my database and I don't understand what am I doing wrong.
I get an exception on the line:
command.ExecuteNonQuery();
The code is:
try
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=UniversityManager;Integrated Security=True");
using (connection)
{
//SqlCommand command = new SqlCommand(
// "INSERT INTO Students VALUES(#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp);",
// connection);
connection.Open();
String sql = "INSERT INTO Students(Id,Name,Surname,Year,PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters["#Id"].Value = 5;
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = collection.Name;
command.Parameters.Add("#Surname", SqlDbType.VarChar);
command.Parameters["#Surname"].Value = collection.Surname;
command.Parameters.Add("#Year", SqlDbType.Int);
command.Parameters["#Year"].Value = collection.Year;
command.Parameters.Add("#PhoneNumber", SqlDbType.VarChar);
command.Parameters["#PhoneNumber"].Value = collection.PhoneNumber;
command.Parameters.Add("#Cnp", SqlDbType.VarChar);
command.Parameters["#Cnp"].Value = collection.Cnp;
command.ExecuteNonQuery();
connection.Close();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thank you!
YEAR is a reserved keyword for Sql Server. So, if you really have a column with that name, then you need to enclose it in square brackets every time you refer to it. Better change that name
String sql = "INSERT INTO Students(Id,Name,Surname,[Year],PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
Another possibility is the Id column. If this column has the IDENTITY property set to true, then you should not set a value for it. It is automatically calculated by the database engine.
Looking at your innerexception message, it seems the problem is due to one or more of your parameters contains more text than allowed by the database field size.
You could try something like this (for each varchar parameter)
// Assuming the Name field is defined as varchar(15)
command.Parameters.Add("#Name", SqlDbType.VarChar, 15);
command.Parameters["#Name"].Value = collection.Name;
The String or binary data would be truncated exception means you're trying to insert a value that is too large for one of the columns in your Student table. For example, your Name field has a maximum length of 10 but you're trying to insert a 15 character name.
Check the values you're inserting and see if they're too large for the columns.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=SALE7\\SALE7;Initial Catalog=YOUTUBE;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (#FIRSTNAME,#LASTNAME)", cs);
da.InsertCommand.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#LASTNAME", SqlDbType.VarChar).Value = textBox2.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery(); // Error occurs here
cs.Close();
}
The exception detail:
Column name or number of supplied values does not match table
definition.
The problem is you may have more than two columns in your table but you have missed to include
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts(FIRSTNAME,LASTNAME) VALUES (#FIRSTNAME,#LASTNAME)", cs);
The exception is telling you what is wrong:
Your table does not have two columns (my guess: it has more).
So, if you just have an ID element with autoincrement, you may change your Command to
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts (firstname,lastname) VALUES (#FIRSTNAME,#LASTNAME)", cs);
you should use insert query like this
INSERT INTO tblContacts(first_name_column_name, last_name_column_name) VALUES (#FIRSTNAME,#LASTNAME)
this error raised because you have more than 2 columns in your table and database couldn't know which columns you try to fill
You might have more the more than two column as you specify.
use query like:
Insert INTO tblContacts(firstname,lastname) VALUES (#firstname,#lastname)
I have posted the code I have below
I am trying to get the data from an Access 2002-2003 database
If I take out everything after the WHERE clause and just use "SELECT * FROM [{0}] then it takes all the data from the table with no problems. I have double checked the field names, they are definitely correct. I have more than 1 table with the same field names, so I thought maybe I would need to include the table name before the field name, but with or without the table I still get the same exception. I have tried moving the position of the square brackets, again with no success...
Even if I include only one of the WHERE clauses, the code no longer works, and I can't for the life of me work out why.. I have spent hours looking at numerous posts here and on other sites related to this error, but none of the suggestions have helped me..
The Destination field is a 'memo' field in Access.
The Next Collection fields are date fields, GVars.currentDate is set earlier in the code to be today's date (with the time portion set to 00:00:00).
GVars.thisFY is also set programatically as a string prior to this.
Any tips would be appreciated.
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE {0}.[Destination] = #Destination AND {0}.[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
// Add values to the fields
cmd.Parameters.AddWithValue("#Destination", "Henwood");
cmd.Parameters.AddWithValue("#NextCollectionA", GVars.currentDate);
cmd.Parameters.AddWithValue("#NextCollectionB", GVars.currentDate.AddDays(1));
adapter = new OleDbDataAdapter(cmd.CommandText, conn);
System.Diagnostics.Debug.Print(cmd.CommandText);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
catch (Exception ex)
{
}
EDIT:
Thanks Vladislav for the answer, corrected code posted below:
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE [{0}].[Destination] = #Destination AND [{0}].[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
// Add values to the fields
cmd.Parameters.Add("#Destination", OleDbType.Char).Value = "Henwood";
cmd.Parameters.Add("#NextCollectionA", OleDbType.DBDate).Value = GVars.currentDate;
cmd.Parameters.Add("#NextCollectionB", OleDbType.DBDate).Value = GVars.currentDate.AddDays(1);
adapter = new OleDbDataAdapter(cmd);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
Try to specify types for the parameters you add.
Another thing I notice is that to your adapter you are passing only the CommandText.
You should pass the whole command object.
In the following example, I have to enter all the details to save the data in the database. Is it possible to leave some textboxes empty save it then use Update command parameters to fill out rest of the data? For example insert ID, AgeGroup, Gender, leave photo and Resume empty and save it in Access database? Could someone provide a example if the you don't mind. The description I have given you I don't know how to describe in technical terms? Thanks in advance for any help.
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence, photo, CV)
VALUES(#ID, #AgeGroup, #Gender, #CriminalOffence, #photo, #Resume)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID",textBox1.Text);
cmd.Parameters.AddWithValue("#AgeGroup", comboBox1.Text);
cmd.Parameters.AddWithValue("#Gender", comboBox2.Text);
cmd.Parameters.AddWithValue("#CriminalOffence", OleDbType.WChar).Value = str;
if (pictureBox1.Image != null)
{
//using MemoryStream:
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
cmd.Parameters.AddWithValue("#photo", photo_aray);
}
cmd.Parameters.AddWithValue("#Resume", richTextBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
VS 2010 C#
Access 2003
Add a checking statement before submission:
for eg:
cmd.Parameters.AddWithValue("#ID", string.IsNullOrEmpty(textBox1.Text.Trim())? DBNull.Value:textBox1.Text.Trim());
You need to pass value to handle error "No value given for one or more required parameters".
it may be DBNull or empty string.
have you set the allow null property to true for the columns that you wanna update later in your database? if not do it and the current code of yours will work fine i guess..
string command = stirng.Format("INSERT INTO Table1(ID, AgeGroup) VALUES ({0},{1})",TextBox1.Text,ComboBox1.Text)
OleDbCommand cmd = new OleDbCommand(command, con)
I basically want to store some values into the database.
I keep getting the error "Number of query values and destination fields are not the same."
pointing towards the dr = cmd.ExecuteReader();
Can someone please help me? :)
I am kinda new to the whole thing and don't really know whats happening.
Bellow is the code am using.
public partial class Registeration_experiment : System.Web.UI.Page
{
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
cmd.Parameters.AddWithValue("#p4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Thank you :)
You are writing to the database, not reading from it.
No sense to use ExecuteReader, you need a ExecuteNonQuery for that
EDIT
Seeing now the structure of the table. It is composed of 5 fields.
In this case, you have two choices. Provide the name of the fields that you want to update in the insert statement or add a parameter for every field
First choice, you don't give the name of the fields
(pass a parameter for every field except the ID because I suppose it is an AutoIncrement field, meaning that the database manages itself the value for that field)
// No name provided for fields, need to pass a parameter for each field
string str = "insert into Registeration_Test values (?, ?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p3", Textbox3.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
(Note, the TextBox1... etc are the names you have provided in you example above, I don't know the exact content of these textboxes where the user types the data to insert in the database, nor I don't know if they really exists in your page/form)
Second choice, you declare the fields that should be updated in the database
// Just three named fields updated
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
Please note also that I have changed your sql command to not use string concatenation.
It is a very bad practice that leads to numerous problem. The worst one is Sql Injection, not to mention problems with string parsing when text contains single quotes or other problematic characters
A parameter placeholder is represented (in OleDb) by the ? in the command text. This placeholder will be replaced by the actual value added in the parameter collection of the OleDbCommand (in the exact order in which the placeholders appears). Using Parameters (Parametrized query) allows the framework to examine the values passed and take appropriate actions if these values are invalid.
EDIT
The problem with connection arises from a previous command that has left the connection open. This is another bad practice. Every connection should be: created, opened, used, closed. The pseudocode to follow is this
// Create the connection
using(OleDbConnection con = GetOleDbConnection())
{
con.Open();
... // use the connection with insert/delete/update/select commands
}
// Exiting from the using block close and destroy (dispose) the connection