I am using a Visual Studio 2010 and ASP.net c# language.
I am try to read from excel sheet then insert the information to the Microsoft SQL database, but I found a problem it ignoring the error in the query statement.
for (int i = 0; i < objdatasetdto.Tables[0].Rows.Count; i++)
{
start_time = Convert.ToDateTime(objdatasetdto.Tables[0].Rows[i]["start"].ToString());
end_time = Convert.ToDateTime(objdatasetdto.Tables[0].Rows[i]["end"].ToString());
if (objdatasetdto.Tables[0].Rows[i]["Lecture_day"].ToString().Equals("1"))
{
try
{
query = "Insert into [M].[Lecture]([dd],[start_time],[end_time],[week_no],[sec_no],
[room_no],[building_no]) "+
values('" + Calendar1.SelectedDate.ToShortDateString() + "','" +
start_time.ToShortTimeString() + "','" + end_time.ToShortTimeString() +
"','1','" + objdatasetdto.Tables[0].Rows[i]["section_no"].ToString() + "','"
+ objdatasetdto.Tables[0].Rows[i]["room_no"].ToString() + "','"
+ objdatasetdto.Tables[0].Rows[i]["building_no"].ToString() + "');";
ifexist = new SqlCommand(query, cnn);
}
catch (Exception ex)
{
Response.Write(ex);
}
}//end if
}// end for loop
I wrote [dd] column instead of [date] to test if it detect the error or not. but it just ignores them completely.
How can I solve this problem.
You don't appear to be executing the SqlCommand. Try adding:
ifexist.ExecuteScalar();
where you have executed the query?
You have not written anything in one of the following
ifexist.ExecuteScalar();
ifexist.ExecuteNonQuery();
If you don't execute you query how the query will be compiled and how will you expect an error.
Related
I´m using C# Windows forms application and i got 5 items in a checklistbox.
Now I have to save these items into a MS Access database table.
Does anyone knows how i should do it?
(Sprachen = checkedlistbox)
private void button1_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Employee (Vorname, Nachname, Wohnort, Geburtstag, Abteilung, Nummer, MKZ, Führerschein, Sprachen) values('" + Vorname.Text + "','" + Nachname.Text + "','" + Wohnort.Text + "','" + Geburtstag.Text + "','" + Abteilung.Text + "','" + Mitarbeiter.Text + "','" + MKZ.Text + "'," + Führerschein.Checked.ToString() + "," + Sprachen.SelectedItems + ")";
command.ExecuteNonQuery();
MessageBox.Show("Daten gespeichert!");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
everytime i tried it with toString(), it gives me an error:
For at least one required parameter no value was specified.
I can only count how many items i´ve checked in the checklistbox.
Anyone got an solution?
Sprachen.SelectedItems returns list of selected items. If you are trying to insert the items which are checked in checkedlistbox then you have to loop for checklistbox.CheckedItems.
Instead of "Sprachen.SelectedItems" pass checklistbox.CheckedItems[0].ToString() as value and check the code. Note: 0 is hard coded.. later you can loop it
String type value must be passed within single quote. Check out last two fields.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i'm a student in a vocational highschool and a newbie programmer..
i have some problem with using loop in my insert query..
i have two table, Book and Book_detail, wich link with foreign key, and i want to save data to both table, and the problem is every time i add a book, i have a textbox named copies_txt, the idea is i want to save the same book_id and the same location_id in the book_detail table but with diffrent boookdetail_id as much as the amount i insert in copies_txt.. and to achieve that i try using for loop, but i gives me error
duplicate entry for key Primary
, here's my full code
int copies = Convert.ToInt32(copies_txt.Text);
int i;
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "insert into simbada_perpustakaan.book(book_id,title,release_date,genre,author,copies,create_by,create_date) values ('" + this.book_id.Text + "','" + this.title_txt.Text + "','" + this.time.Text + "','" + this.genre_txt.Text + "','" + this.author_txt.Text + "','" + this.copies_txt.Text + "','" + this.username_lbl.Text + "','" + DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss") + "') ; ";
string Query2 = "insert into simbada_perpustakaan.book_detail(id_bookdetail,book_id,location_id) values('" + Guid.NewGuid() + "','" + this.book_id.Text + "','" + this.textBox1.Text + "') on duplicate key update id_bookdetail=(id_bookdetail=('"+Guid.NewGuid()+"'))";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
conDataBase.Close();
for (i = 0; i <= copies; i++)
{
conDataBase.Open();
myReader = cmdDataBase2.ExecuteReader();
conDataBase.Close();
}
MessageBox.Show("saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
can somebody please point out my mistake... thanks before.
I think your issue is with the second query. Move the query inside the loop and check. Also you don't need a data reader since it's a select statement. Also you can avoid multiple database open and close statement. Try below code
int copies = Convert.ToInt32(copies_txt.Text);
int i;
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "insert into simbada_perpustakaan.book(book_id,title,release_date,genre,author,copies,create_by,create_date) values ('" + this.book_id.Text + "','" + this.title_txt.Text + "','" + this.time.Text + "','" + this.genre_txt.Text + "','" + this.author_txt.Text + "','" + this.copies_txt.Text + "','" + this.username_lbl.Text + "','" + DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss") + "') ; ";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
cmdDataBase.ExecuteNonquery();
for (i = 0; i <= copies; i++)
{
string a = Guid.NewGuid().ToString();
string Query2 = "insert into simbada_perpustakaan.book_detail(id_bookdetail,book_id,location_id) values('" + a + "','" + this.book_id.Text + "','" + this.textBox1.Text + "') on duplicate key update id_bookdetail=(id_bookdetail=('"+a+"'))";
MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase);
cmdDataBase2.ExecuteNonQuery();
}
MessageBox.Show("saved");
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Also always try to do parameterized query. That can avoid sql injection problem.
Let,
first Guid.NewGuid() = 'zxcvbnm'
second Giud.NewGuid() = 'asdfghjkl'
book_id = 2
location_id = 3
After executing Query2 we get the string like
insert into book_detail(id_bookdetail,book_id,location_id) values('zxcvbnm','2'
,'3') on duplicate key update id_bookdetail='asdfghjkl';
when we try to execute it at for loop then
When i = 0
It inserts data fine as id_bookdetail('zxcvbnm') is unique.
When i = 1
It also inserts data fine because id_bookdetail('zxcvbnm') is used ago but using on duplicate key id_bookdetail set a new value('asdfghjkl') which is unique.
But When i = 2
It gives you error because first he gets id_bookdetaidid('zxvbnm') as duplicate, then he try to use second one('asdfghjkl') which is also duplicate. So it gives you that error.
A little noob says HY.
I have a small problem with a homework project in Microsoft Visual Studio 2010.
Also, i work in C#.
I must do a site for selling products and i have an Access database.
So, the problem is this: i wrote code but it seems something is wrong and i don't know what!
When i try to Add a command by site i receive an error:
Data type mismatch in criteria expression.
Code is:
string date = DateTime.Now.ToShortDateString();
string string_baza_de_date = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\BogCs\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\magazin.mdb";
OleDbConnection ConexiuneSQL = new OleDbConnection(string_baza_de_date);
ConexiuneSQL.Open();
int numar_total_de_produse = CheckBoxList1.Items.Count; // se numara produsele
for (int i = 0; i < numar_total_de_produse; i++) // de la primul articol din CheckBoxList1 pana la ultimul
{
if (CheckBoxList1.Items[i].Selected == true) // daca am selectat un produs
{
// interogarea comenzii:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ("
+ TextBox1.Text + ",'" + TextBox2.Text + "',"
+ CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"
+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString() + "');";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.ExecuteNonQuery();
}
}
ConexiuneSQL.Close();
GridView3.Visible = false;
Button1.Visible = false;
Button2.Visible = false;
CheckBoxList1.Visible = false;
Label1.Visible = false;
TextBox1.Visible = false;
Label2.Visible = true;
When i press "Add command" gives me that error and i don't know how to solve!
you have to put " ' " before and after textbox1.text
so it would look like this:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "', " + CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString()+ "');";
Probably the error lies in some of your strings used to build the command.
As usual this is the first obvious reason to use parametrized query.
Let the framework code format your strings according to the rules of the current database.
The most important reason however, is the Sql Injecton problem
So let me change your code in this way to get rid of that ugly string concatenation
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, "+
"ID_produs, produs, tip_produs, data_comanda, pret) " +
"VALUES (?,?,?,?,?,?,?)";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.Parameters,AddWithValue("#p1",TextBox1.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p2",TextBox2.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p3",CheckBoxList1.Items[i].Value );
comanda_inserare_comanda.Parameters,AddWithValue("#p4",CheckBoxList1.Items[i].Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p5","Televizoare LED");
comanda_inserare_comanda.Parameters,AddWithValue("#p6",data_curenta);
comanda_inserare_comanda.Parameters,AddWithValue("#p7",GridView3.Rows[i].Cells[3].Text.ToString());
comanda_inserare_comanda.ExecuteNonQuery();
Also, keep in mind that you should pass the value to the parameters with the correct datatype expected by the database field. For example, if your first field ID_comanda is numeric then the line of the relative parameter should be changed to
comanda_inserare_comanda.Parameters,AddWithValue("#p1",Convert.ToInt32(TextBox1.Text));
and this raises another problem. Did you check if the text in the TextBox1 is really a number?
SqlConnection con = new SqlConnection(GlobalData.GetConnectionString());
string queryDepartment = null;
if (rbtnYes.Checked == true)
{
if (rbtnMale.Checked == true)
{
queryDepartment =
#"BEGIN TRY
BEGIN TRAN
insert into UserDetails
values('" + Convert.ToInt32(txtID.Text) + "','" + txtFullName.Text + "','" + txtPassword.Text + "','" + txtUserName.Text + "','" + cbDepartment.SelectedValue.ToString() + "','" + txtContactAddress.Text + "','" + Convert.ToInt64(txtContactNumber.Text.ToString()) + "','" + txtContactEmail.Text + "',CAST(GETDATE() AS DATE),'" + rbtnYes.Text + "',null,'" + rbtnMale.Text + "','" + Convert.ToInt64(txtSalary.Text.ToString()) + #"');
insert into Users
values('" + GlobalData.UsersID_AddUsers + "','" + GlobalData.RoleID_AddUsers + "','" + txtUserName.Text + "','" + Convert.ToInt32(txtID.Text) + #"');
COMMIT TRAN
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage
IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION
END CATCH";
}
}
i am trying to insert records using sql transaction into two table from c# code but it is not working.
while the same statement i am inserting in sql table using sql management software its working.
Your SQL starts with a BEGIN but has no matching END. You do not need the BEGIN - remove it.
Since you said there are no errors come out then i guess this is the problems, your condition doesnt match, would you mind to put a debugged point to check is your condition matches to call your insert function?
if (rbtnYes.Checked == true)
if (rbtnMale.Checked == true)
Thank You Every One I have Solved My Problem My Own.........
the problem is the
GlobalData.RoleID_AddUsers is 0..
but because of sql try catch its not showing me the error....or catching the exception....
but when i removed the sql try catch...then its start throwing the exception saying that foreign key violation....and bla bla........and i adjust the code as per the requirement....
and problem solved......:)
I keep getting this error:
Invalid object name "CAccounts".
and the code I have is:
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
// Set ConnectionString.
String sConSg =
"CONNSTRING HERE";
using (SqlConnection connection = new SqlConnection(sConSg))
{
try
{
connection.Open();
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
try
{
SqlDataReader slrr = null;
SqlCommand command = new SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode = " +
"'" + _activationcode.Text + "'", connection);
slrr = command.ExecuteReader();
while (slrr.Read())
{
if (slrr["ActivationCode"].ToString() == _activationcode.Text)
{
MessageBox.Show(slrr["ActivationCode"].ToString(), "AutoOptimise");
}
else
{
}
}
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
}
});
thread.Start();
Can somebody please shed some light?
The table CAccounts you're referencing in your select clause probably doesn't exist in the database. Check that.
See a list of possibilities here:
http://web.archive.org/web/20150519073601/http://sqlserver2000.databases.aspfaq.com:80/why-do-i-get-object-could-not-be-found-or-invalid-object-name.html
I'd suggest these things:
check which schema the object CAccounts is under. Is it dbo or other? Does the user have permissions on that schema?
login to SQL Server via Management Studio. Use the credentials in the connection string that the code is using. Paste & run the SQL statement above.
use SQL Profiler to capture/verify ensure the SQL statement as it crosses to your SQL Server. Run THAT as an adhoc query against that SQL Server.
are there any funny DNS issues? Hosts files? Does this happen during debugging or on the app server?
is the database server name correct? i.e. localhost versus a named server. Try addressing by the IP address that you expect it to be run at, just for fun, both in your connection string, and via SSMS.
Instead of CAccounts, I had to label it DATABASENAME.dbo.CAccounts.
So it would be something like:
"SELECT * FROM DATABASENAME.db.CAccounts"
This might work:
SqlConnection con = new SqlConnection("Data Source=192.168.1.12;Initial Catalog=Ibrahim;User ID=sa;Password=1412;");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Ibrahim.EVC_Activation_Val (Date,Dealer,Transaction_ID,Invoice_ID,Mobile_Num,Quantity_LE) values('" + DateTimePicker1.Value.ToString("yyyy/mm/dd") + "','" + Txtbx1.Text + "','" + Txtbx2.Text + "','" + Txtbx3.Text + "','" + Txtbx4.Text + "','" + Txtbx5.Text + "')",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
con.Close();