Access database and C# issues with auto increment primary key - c#

I have a form with first name , last name , email, supervisor. I then have my code behind on button set to this
private void agentInsertButton_Click(object sender, EventArgs e)
{
try
{
ad.InsertCommand = new OleDbCommand("insert into Agents values ([FirstName],[LastName],[Email],[Supervisor])", con);
ad.InsertCommand.Parameters.Add("#FirstName", OleDbType.VarChar).Value = agentNametextBox1.Text.ToString();
ad.InsertCommand.Parameters.Add("#LastName", OleDbType.VarChar).Value = agentLastNametextBox4.Text.ToString();
ad.InsertCommand.Parameters.Add("#Email", OleDbType.VarChar).Value = agentEmailtextBox3.Text.ToString();
ad.InsertCommand.Parameters.Add("#Supervisor", OleDbType.VarChar).Value = agentSupervisortextBox2.Text.ToString();
con.Open();
ad.InsertCommand.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
};
I am getting error number of query values and destination fields are not the same . I am sure it is how I have the DB sending over the variables and the AgentID causing the issue. I am new to access but that is what my work is wanting to use. Look forward to a solid answer.
I am just using a simple access database named Agents
Fields are
AgentID - auto number
FirstName - text
LastName - text
Email - text
Supervisor - text

When you write an INSERT statement it must either be like this:
INSERT INTO TableName VALUES (ValueList)
in which case you must provide values for every column and in the order that they were added to the table, or like this:
INSERT INTO TableName (ColumnList) VALUES (ValueList)
in which case you can specify a subset of the columns and in any order. You have done neither. You have done this:
INSERT INTO TableName VALUES (ColumnList)
which is meaningless. Your SQL needs to be like this:
insert into Agents ([FirstName],[LastName],[Email],[Supervisor]) values (#FirstName,#LastName,#Email,#Supervisor)
Note that the values now match the parameters that you add to the command.

Change your query like this
ad.InsertCommand = new OleDbCommand("insert into Agents values (#FirstName,#LastName,#Email,#Supervisor)", con);
or
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName,LastName,Email,Supervisor) values (#FirstName,#LastName,#Email,#Supervisor)", con);

OleDb is index-based and doesn't use named parameters.
Change as follows:
ad.InsertCommand = new OleDbCommand("insert into Agents (FirstName, LastName, Email, Supervisor) values (?, ?, ?, ?)", con);
ad.InsertCommand.Parameters.AddWithValue("?", agentNametextBox1.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentLastNametextBox4.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentEmailtextBox3.Text);
ad.InsertCommand.Parameters.AddWithValue("?", agentSupervisortextBox2.Text);

Related

C# code to insert values into a database not working

This is the button for inserting those fileds into my database, the field names and db connection works for any other tasks but somehow this button keeps telling me the insert failed"
private void button1_Click(object sender, EventArgs e)
{
try {
int answer;
sql = "INSERT INTO Registration VALUES (#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)";
connection.Open();
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#Student_ID", comboBox1.SelectedItem.ToString());
command.Parameters.AddWithValue("#Course_ID", lstcourse.SelectedItem.ToString());
command.Parameters.AddWithValue("#Section", txtsection.Text);
command.Parameters.AddWithValue("#Start_Date", txtstart.Text);
command.Parameters.AddWithValue("#End_Date", txtend.Text);
command.Parameters.AddWithValue("#Semester", txtsemester.Text);
answer = command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("You're awesome and added " + answer + " row to your registration");
}
catch
{
MessageBox.Show("You screwed up");
}
/////////////////////////////////
}
This is the table:
Registration_ID float Checked
Student_ID float Checked
Course_ID float Checked
Section float Checked
Start_Date datetime Checked
End_Date datetime Checked
Semester nvarchar(255) Checked
Unchecked
Somehow this button keeps telling me the insert failed
It would of been helpful if you could have posted the actual error from the catch statement. If you debugged the routine and specifically inspected the error message, you'd notice what was wrong.
The primary issue of the error is because you didn't supply the columns to insert into. If you supplied all columns upfront the insert statement would be satisfied and work just fine.
Solution
Either make sure all columns are accounted for in the insert statement.
Specify the columns you are inserting into.
Your table according to your post has 7 columns, you are only supplying 6 of them. When you using the syntax of INSERT INTO TABLENAME VALUES() you have to supply values for all columns, not just a select few.
On the other hand if you used the syntax of INSERT INTO TABLENAME(columnName, columnName)VALUES(value, value) you are fulfilling the requirements by supplying two columns along with their values.
Side Note:
Look into using statements to ensure objects are disposed of.
Use SqlParameterCollection.Add method instead of AddWithValue, it has to infer the data types and this could cause unintended results.
When declaring your parameters, please specify/add the correct data type and length that matches the column data type and length on the table.
Either modify your SQL statement to include the missing column:
INSERT INTO Registration VALUES (#Registration_ID,#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)
or specify the columns that will be populated in your new row (assuming your Registration_ID field is an auto-identifier)
INSERT INTO Registration (Student_ID, Course_ID, Section, Start_Date, End_Date, Semester) VALUES (#Student_ID,#Course_ID,#Section,#Start_Date,#End_Date,#Semester)
you can try this code
using(SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO Table(id,name,test)
VALUES(#param1,#param2,#param3)";
using(SqlCommand cmd = new SqlCommand(sql,connection))
{
cmd.Parameters.Add("#param1", SqlDbType.Int).value = val;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = Name;
cmd.Parameters.Add("#param3", SqlDbType.Varchar, 50).value = Test;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}

Datarow id string not matching with object id string even though they are identical strings after checking debug

I am trying to search through a list of ID strings in my database where an ID string is equal to the one of the object i am trying to create. The id being created is in a factory design pattern where a train type "express" is made with an ID of "1E45". After this ID is created, it increments the number section after the letter and then that can be used for the next train added.
When searching through the list with a foreach it returns the id from the database that is similar to the one trying to be created.
But when I try to match these two after using toString to change them both and match in an IF. The match returns false even though when I check the debug it is exactly the same?
It then just continues on to try and add a new object with that ID that already exists and crashes.
What am I doing wrong? it doesn't make sense after checking the values being matched and it saying false.
Here is the code I have set up:
//Create sql command variables to create new commands
SqlCommand insert = new SqlCommand();
SqlCommand checkID = new SqlCommand();
//Set the command type to text
insert.CommandType = CommandType.Text;
checkID.CommandType = CommandType.Text;
//Searches for an ID in the database that matches one that is trying to be created
checkID.CommandText = "SELECT id FROM Train WHERE id = #trainID";
//Parameters for checking ID in database
checkID.Parameters.AddWithValue("#trainID", train.TrainID);
//Set the connection for the command for the checkID sql connection
checkID.Connection = con;
//Start the connection
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(checkID);
adapter.Fill(dt);
dt.Load(checkID.ExecuteReader());
//Item last = Module.
foreach (DataRow i in dt.Rows)
{
if (i.ToString() == train.TrainID.ToString())
{
MessageBox.Show("This ID already exists! " + train.TrainID);
return;
}
}
//Close the connection
con.Close();
//Set the text for the command to insert data to the database connected to
insert.CommandText = "INSERT Train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( #trainID , #departure, #destination, #type, #intermediate, #dep_time, #dep_date, #sleep, #first)";
//Parameters for adding values from the train object to the database
insert.Parameters.AddWithValue("#trainID", train.TrainID);
insert.Parameters.AddWithValue("#departure", train.Departure);
insert.Parameters.AddWithValue("#destination", train.Destination);
insert.Parameters.AddWithValue("#type", train.Type);
insert.Parameters.AddWithValue("#intermediate", intStops);
insert.Parameters.AddWithValue("#dep_time", train.DepartureTime);
insert.Parameters.AddWithValue("#dep_date", train.DepartureDay);
insert.Parameters.AddWithValue("#sleep", train.SleeperBerth);
insert.Parameters.AddWithValue("#first", train.FirstClass);
//Set the connection for the command for the insert sql connection
insert.Connection = con;
//Start the connection
con.Open();
//Execute the command specified
insert.ExecuteNonQuery();
//Close the connection
con.Close();
Sounds like you need to change your column id in the table train to an IDENTITY column, and let the database handle the ID assignment:
ALTER TABLE dbo.Train ALTER COLUMN id int IDENTITY(1,1); --data type guessed
Then, in your application, you don't need to generate a value for ID, nor do declare it in your INSERT statement (either in the list of columns to INSERT into or in your VALUES clause).

I have an Access database, when adding other text boxes I get a connection error

Adding information to a Access data base worked well with 2 textboxes the "Name" and "Phone" when I add other textbox to the database, I get a connection error
An unhandled exception of type'System.Data.OleDb.OleDbException' occurred in System.Data.dll
I get this error when inserting new data. The datagrid shows the new fields added, I can read the data I just cant add.
private void button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+txtName.Text+"','"+txtPhone.Text+"','"+txtClockNumber.Text+"','"+txtCostCenter.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
txtName.Text = "";
txtPhone.Text = "";
txtClockNumber.Text = "";
txtCostCenter.Text = "";
MessageBox.Show("record inserted successfully");
}
You have mistake in your query as #WayneG.Dunn have mentioned
This:
"insert into table1 values('"+txtName.Text+"','"+txtPhone.Text+"','"+txtClockNumber+"','"+txtCostCenter+"')"
Must be:
"insert into table1 values('"+txtName.Text+"','"+txtPhone.Text+"','"+txtClockNumber.Text+"','"+txtCostCenter.Text+"')"
Also here is part of the article about how to insert values in MS Access.
To add one record to a table, you must use the field list to define which fields to put the data in, and then you must supply the data itself in a value list. To define the value list, use the VALUES clause.
For example, the following statement will insert the values "1", "Kelly", and "Jill" into the CustomerID, Last Name, and First Name fields, respectively.
INSERT INTO tblCustomers (CustomerID, [Last Name], [First Name])
VALUES (1, 'Kelly', 'Jill')
You can omit the field list, but only if you supply all the values that record can contain.
INSERT INTO tblCustomers
VALUES (1, Kelly, 'Jill', '555-1040', 'someone#microsoft.com')
Source MSDN How to: Insert, Update, and Delete Records From a Table Using Access SQL

Insert statement into SQL Server db

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.

User name can not contain null value

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!

Categories

Resources