Copy Records From Access Table To Access Table - c#

In C# I am trying to insert records from one access table to another access table, but I get the above error message. What is causing this error (OleDbException: No value given for one or more required parameters) as it is a straight Select * statement?
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] SELECT * FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();
EDIT --- Error in Insert Statement
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (Name, Address, Phone, RepeatCustomer) SELECT Name, Address, Phone, RepeatCustomer FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();

Are the two tables identical? You'd get this error if the column order and/or types don't match. It's much better form to explicitly define the columns you want to modify:
INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (col1,col2) SELECT col1,col2 FROM table1 WHERE company = 2
this way, order doesn't matter, and you aren't trying to add to columns that don't exist.

I had the same issue copying to the same table. This sample of just two fields worked for me:
INSERT INTO [Orders] (CUST, PART_NUMBE) SELECT CUST, PART_NUMBE FROM [orders]
WHERE [OrderNumber]= 23979

Related

Insert foreign key into table with SQL query using C#

I have a database with 3 tables Identification, Identification_group and Group.
The Identification_group table has 2 foreign key columns, Identificaiton_id and Group_id.
In my form you can select the Group Number and it returns the right Group_id to the Identification_group table.
Is it possible to write a SQL query that uses the last Identification_id and the Group_id (from the selection field in my form) and writes this to the Identification_group table?
string sqlquery1 = "Insert into [dbo].[identification_group] (fk_group_id,fk_identification_id values (#fk_group_id,#fk_identification_id;";
SqlCommand schreiben = new SqlCommand(sqlquery1, myConnection);
myConnection.Open();
schreiben.Parameters.AddWithValue("#fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("#fk_group_id", Wil_Jls_idComboBox.SelectedValue);
schreiben.CommandText = sqlquery;
schreiben.ExecuteNonQuery();
myConnection.Close();
Sorry for the bad formatting, first time posting here.
Thank you in advance
Please try the below:
You have an issue with your SQL statement whereby you did not close the brackets. Also, you only need the # symbol in the SQL statement, and not in the C# code.
// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (#fk_group_id, #fk_identification_id)";
// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);
// Open the SQL connection
myConnection.Open();
// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);
// Bind the command
schreiben.CommandText = query;
// Execute the command
schreiben.ExecuteNonQuery();
// Close the connection
myConnection.Close();

How to insert data into sql server database when the primary key column already set default identity(1, 1)

I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();
Cannot insert the value NULL into column OrderID, table RestaurantApp.dbo.Junc_Order; column does not allow nulls. INSERT fails.
The OrderID column is actually the primary key in my data table. I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.
Here is the part of my code:
string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (#ID, #Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#ID", r_ID);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I already get connection with database ahead of these codes, so the problem should not be that.
Updated Junc_Order table design:
OrderID (PK,FK,int,not null)
ID(FK,int,not null)
Quantity(int,not null)
By viewing your question, it seems that your insert query is not correct:
First of all, you don't need to insert "OrderID" as it is primary key identity so sql server automatically insert it.
second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:
string insertString = "INSERT INTO Junc_Order(Quantity) values(#Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();

Insert a value in a table from another table using a variable in C# , SQL Server

I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

How do I insert a record into multiple tables in a database

I'm self studying in C# and SQL Server 2005
I have 3 tables in SQL Server 2005 and I have a form in C# that accept inputs to be saved in the database.
My 3 tables are
Hotel with columns Hotel No, Hotel Name, Location
Guest with columns Guest No, Guest Name, Address
Room with columns Room No Room Type, Room Price
and a junction table where all three tables meet
Booking Hotel No, Guest No, Room No, Date From, Date To
I set the relationship that Hotel No, Guest No, Room No are foreign key to Booking table
In my C# form, I have a code that fills the combo box for Hotel Name and Room Type
private void FillComboBoxHotelName()
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Hotel", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
da.SelectCommand.CommandText = cmd1.CommandText.ToString();
DataTable dt = new DataTable();
da.Fill(dt);
cmbHotelName.DataSource = dt;
cmbHotelName.DisplayMember = "Hotel Name";
cmbHotelName.ValueMember = "HotelNo";
conn.Close();
}
private void FillComboBoxRoomType()
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Room", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.CommandText = cmd.CommandText.ToString();
DataTable dt = new DataTable();
da.Fill(dt);
cmbRoomType.DataSource = dt;
cmbRoomType.DisplayMember = "Room Type";
cmbRoomType.ValueMember = "RoomNo";
conn.Close();
}
This code works and the records in my tables in Hotel and in Room fills the combo box in my form, my problem now is how do I store the input values in the Form to my database. Do I need to create a separate Insert query command for each table since the data will go to 3 tables, I am at lost.
My form looks like this:
Hotel Name : Combo Box
Guest Name:
Guest Address:
Date From:
Date To:
Room Type:
Button (Save)
Please help I still cant post an image.
There are two approaches to achieve it Insert Statement and Stored Procedures.
Insert
string sql = "INSERT INTO Hotel (Hotel No, Hotel Name, Location) values (#HotelNo,#HotelName,#Location)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#HotelNo", SqlDbType.Int);
cmd.Parameters.Add("#HotelName", SqlDbType.VarChar);
cmd.Parameters.Add("#Location", SqlDbType.VarChar);
cmd.Parameters["#HotelNo"].Value = HotelNo; // Hotel number name in Int
cmd.Parameters["#HotelName"].Value = HotelName;//Hotel Name in string
cmd.Parameters["#Location"].Value = Location;//Location in form of text
cmd.ExecuteNonQuery();
Note: Here in code I have made some assumptions that Hotel No is Int, Hotel Name is VarChar and Location is VarChar.
In similar way you can create Insert statement for rest of 2 tables and Insert code into 2 tables.
Stored procedure
Create stored procedure to all columns you want to insert into database. Like
CREATE PROCEDURE yourInsertOperation
-- Add the parameters for the stored procedure here
#HotelNo INT,
#HotelName VARCHAR(20),
#Location VARCHAR(20),
--......rest of all your parameter list goes here
AS
BEGIN
INSERT INTO resourceTable(column1, column2) VALUES (#HotelNo, #HotelName, #Location )
--Other 2 insert statements will go here
End
Go
Once your stored procedure is in place in your Data Base. You can call that stored procedure along with parameters from C# code.
SqlCommand cmd = new SqlCommand("yourInsertOperation",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#HotelNo", SqlDbType.Int);
cmd.Parameters.Add("#HotelName", SqlDbType.VarChar);
cmd.Parameters.Add("#Location", SqlDbType.VarChar);
//Other columns to insert will go here
cmd.Parameters["#HotelNo"].Value = HotelNo; // Hotel number name in Int
cmd.Parameters["#HotelName"].Value = HotelName;//Hotel Name in string
cmd.Parameters["#Location"].Value = Location;//Location in form of text
//Values for columns will go here
cmd.ExecuteNonQuery();
To summarize I would suggest you to go with Insert query as it will easy and quick approach to insert into database. And in this you don't have to put efforts in creating SP. But still you have choice to use any or both approaches as your doing it for learning purpose.
There is multiple way to solve your question:
Create trigger on insert in table Booking which will populate rest of the related tables
Put insert SQL in your C# for each involved tables, not the best way to do this but it can be done.
Build store procedure to do insert in all 4 tables sequentially. Call this SP from your C# code.
I would prefer to use either 3 or 1 options in order of preference.

" Error in connection" when use insert command to access db with ado.net C#

I write code to insert some values to access database with C#/ado.net but there is an error appear called "error in connection" although i use select command to retrieve some valuesin the same program and works successfully
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mohamed\documents\visual studio 2012\Projects\Library Store\Library Store\Book.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Store VALUES (#val1,#val2,#val3,#val4,#val5,#val6)", conn);
cmd.Parameters.AddWithValue("#val1", ISBNTB.Text.Trim());
cmd.Parameters.AddWithValue("#val2", NameTB.Text.Trim());
cmd.Parameters.AddWithValue("#val3", GategoryTB.Text.Trim());
cmd.Parameters.AddWithValue("#val4", AuthorTB.Text.Trim());
cmd.Parameters.AddWithValue("#val5", int.Parse(CostTB.Text.Trim()));
cmd.Parameters.AddWithValue("#val6", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show(" Done :)");
conn.Close();
thanks;
Give this a shot, you didn't specify what error it was but this should help you out if anythign figure out if you really have all columns your trying to insert to
Try writing you sql statement like so
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mohamed\documents\visual studio 2012\Projects\Library Store\Library Store\Book.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Store **( Column1, Column2 )** VALUES(#val1,#val2,#val3,#val4,#val5,#val6)", conn);
cmd.Parameters.AddWithValue("#val1", ISBNTB.Text.Trim());
cmd.Parameters.AddWithValue("#val2", NameTB.Text.Trim());
cmd.Parameters.AddWithValue("#val3", GategoryTB.Text.Trim());
cmd.Parameters.AddWithValue("#val4", AuthorTB.Text.Trim());
cmd.Parameters.AddWithValue("#val5", int.Parse(CostTB.Text.Trim()));
cmd.Parameters.AddWithValue("#val6", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show(" Done :)");
conn.Close();
You need to specify the column names in your insert statement so that the DB knows where the data is going.
"INSERT INTO Store (Column1, Column2) VALUES (#val1, #val2)"
If you insert value to database with all column you can use this query
INSERT INTO Store VALUES(#val1,#val2,#val3,#val4,#val5,#val6)
If you insert value to database with few column you will get this error, and you must write it as
INSERT INTO Store **( Column1, Column2 )** VALUES(#val1,#val2,#val3,#val4,#val5,#val6)

Categories