I used the code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("server=kiran-b946c0f6d;
uid=sa;
pwd=123;
database=employe");
SqlCommand com=new SqlCommand("INSERT INTO Emplo VALUES('"+TextBox2.Text+"'",con);
com.Parameters.Add("Email_ID", SqlDbType.VarChar);
com.Parameters["Email_ID"].Value = TextBox2.Text;
con.Open();
Label3.Text = "successfully added";
SqlDataReader reader = null;
com = new SqlCommand("SELECT Email_ID FROM Emplo WHERE Email_ID='"
+ TextBox2.Text + "'",
con);
reader = com.ExecuteReader();
if (reader != null && reader.HasRows)
{
Label3.Text = "Emailid alraedy exist";
}
reader.Dispose();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
I intended to use Insert values in the database and if there is any duplicity,it will show the error.The duplicity is working properly.But insertion is not properly working.It will show inserted successfully.But the values are not doing insertion.
You're not actually calling com.ExecuteNonQuery() before overwriting the com variable.
You aren't running the insert at all - you set up the command and then overwrite it with your new select command.
Even if you were running the insert at that point your select that is coming after it would always be expected to return true because you've just inserted it. Additionally depending on the database structure if that database field is set to be unique (which seems to be what you are trying to enforce in the code) then I would expect a sql exception to be thrown as you try to insert something which already exists.
What you want to do is run the select to check if it already exists first. Then if it exists you can just stop. If it doesn't exist you can do the insert then.
Or better still write a single SQL statement (better yet a procedure) that does the check at the same time as the insert to try to prevent any possible issues relating to two threads doign the check and finding it doesn't exist and then two threads doing the insert causing one of them to fail most likely.
Related
private void btn_view_Click(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
dgv_emptable.DataSource = ds.Tables[0];
con.Close();
}
private void btn_insert_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Insert into tbl_emp(emp_id,emp_name,emp_surname,designation_id,dept_id) Values(" + txt_id.Text + " , '" + txt_name.Text + "','" + txt_phone.Text + "'," + cmb_desigid.SelectedValue + ",'" + cmb_deptid.SelectedValue.ToString() +"')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Record inserted");
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_designation", con);
DataSet ds = new DataSet();
da.Fill(ds);
cmb_desigid.DataSource = ds.Tables[0];
cmb_desigid.DisplayMember = "designation_type";
cmb_desigid.ValueMember = "designation_id";
con.Close();
con.Open();
OleDbDataAdapter db = new OleDbDataAdapter("Select * from tbl_dept",con);
DataSet dm = new DataSet();
db.Fill(dm);
cmb_deptid.DataSource = dm.Tables[0];
cmb_deptid.DisplayMember = "dept_name";
cmb_deptid.ValueMember = "dept_id";
con.Close();
}
I have bound my database and I am writing an insert query to insert data in table but I get the same error at cmd.ExecuteNonQuery
no given parameters are given for required parameters.
I have checked thoroughly but can't seem to find the error
I have used textbox for emp_id,emmp_name,emp_surname,and two combo boxes for designation_id and dept_id.
the dept_id and designation_id are foreign key in tbl_emp. and i also have used the combo box property.So can anyone please tell what the error is and also if i have writtern the combo box code properly...
You need to get in the habit of using "parameterized queries" - those won't just protect your code from the #1 vulnerability out there - SQL injection - they'll also solve a lot of thorny issues with adding quotes etc. to string values.
Try this code:
private void btn_insert_Click(object sender, EventArgs e)
{
// define the insert query - OleDB uses unnamed, positional parameters
string insertQuery = "INSERT INTO tbl_emp (emp_id, emp_name, emp_surname, designation_id, dept_id) " +
"VALUES (?, ?, ?, ?, ?)";
// create command
OleDbCommand cmd = new OleDbCommand(insertQuery, con);
// define parameters - in the proper order! - and set their values
// The "names" like "#emp_id" that I'm using here are just to make it easier for you to grasp which parameter
// corresponds to which columns being inserted - you could also name them "p1", "p2" etc. - not very intuitive, though ...
// Check the *assumptions* I made for the datatypes - not sure if those are
// really what you have - adapt as needed
cmd.Parameters.Add("#emp_id", OleDbType.Int).Value = Convert.ToInt32(txt_id.Text);
cmd.Parameters.Add("#emp_name", OleDbType.VarChar, 100).Value = txt_name.Text;
cmd.Parameters.Add("#emp_surname", OleDbType.VarChar, 100).Value = txt_phone.Text
cmd.Parameters.Add("#designation_id", OleDbType.Int).Value = cmb_desigid.SelectedValue;
cmd.Parameters.Add("#dept_id", OleDbType.Int).Value = cmb_deptid.SelectedValue;
// open connection, execute query, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted");
}
As a general side note: if you're only ever interested in a single DataTable being returned from a query - I'd strongly recommend using this code (instead of what you have now):
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from tbl_designation", con);
// define and use a "DataTable" - not a "DataSet" (which is overkill for just a single table of data)
DataTable dt = new DataTable();
da.Fill(dt);
cmb_desigid.DataSource = dt;
cmb_desigid.DisplayMember = "designation_type";
cmb_desigid.ValueMember = "designation_id";
con.Close();
I mentioned in the comments that you can get VS to do all this for you, in less time, and more securely/reliably than a human could do in a day. Writing db access code is boring and annoying, here's how you hand it off:
add a new dataset to the project, just like you would add a form or class or any other thing. Call it something sensible, not dataset1
open the server explorer window, and add a connection to your access db
drag the db into the dataset. Thoroughly read the long message box that pops up. No one reads this, and they should read it. It solves a lot of confusion later on when the build process is overwriting the database the exe is saving in, and it looks like your app never saves any data. Click yes
drag some tables out of the server explorer and into the dataset. Not the appearance of a datatabke with all the same columns as your db table and a tableadapter. This thing is NOT your database table, it is a strongly typed client side datatable which is a better version of what you're doing in your code above with weakly typed datasets and datatables. A tableadapter is a better version of a dataadapter designed to work with the better datatable it is visually attached to
switch to the forms designed
open the data sources window from the view menu, other windows submenu
drag one of the nodes out of data sources and onto the form
Many things appear, a data grid view, binding source, navigator, dataset, tableadapter, manager. Don't delete stuff until you understand how it all works because it will teach you a lot. Run the program
This app will work, load data, save data and you didn't so far write any code at all. VS wrote all the code for you and you can read it if you want, it's there in the .Designer.cs files on disk
Run the app, add some rows, change stuff, click save, close the app. Don't run the app again yet, but instead go into the bin/debug folder and open that db on there, in access. See your data you added/changed
Now close access and build the project again, now open the same bin/debug db in access.. see the data has gone? The build process copied the blank db from the project over the top of the db the exe altered when it ran. Make sure you grok what is happening here every time you build or you'll be very confused as to why your app "isn't saving" (it is, but the changes are being wiped by the build process)
Some other things you need to know about tableadapters:
they can have more than one select command- just right click them in the dataset designer and add another query. Use parameters, like SELECT * FROM t WHERE id = #id and give the command a sensible name like FillById. The tableadapter will gain a method myTabkeAdapter.FillById(someDatatableHere, 1234) to fill that datatable with row ID 1234
they have an Update method that takes a datatable. This is NOT JUST for running update queries. Update scans the whole passed on datatable looking for rows that need to be inserted updated or deleted and executes the relevant sql. When you change a datatable row, the change is tracked by the RowState property. If the rowstate is Added, and insert will be run by the table adapter, to insert the row. If the rowstate is Modified, an Update will be run. If the rowstate is deleted, a delete will be run. Microsoft should have called Update something else, like Save, because it causes confusion often
I know this question was asked but I can't figure out why this action is so complex.
So I have a Produs table
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
This is my table's columns. I added via Data Sources GUI from Visual Studio a DataSet with the content of this table (no actual code wrote by me).
Now I have a procedure that will insert me a new row in this Table.
Here is the code:
private void dToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("connection-string-here");
string Query = "spGE_getProduse_Edit"; // Stored procedure name.
int Integer;
conn.Open();
// Creating SqlCommand object
SqlCommand com = new SqlCommand(Query, conn );
// Here we declaring command type as stored procedure:
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#IDProdus", 0);
com.Parameters.AddWithValue("#Denumire ",
denumireTextBox.Text.ToString());
com.Parameters.AddWithValue("#UM ",
uMTextBox.Text.ToString());
com.Parameters.AddWithValue("#Pret ",
Double.Parse(pretTextBox.Text));
com.Parameters.AddWithValue("#IDFurnizor ",
Int16.Parse(iDFurnizorTextBox.Text));
com.Parameters.AddWithValue("#IDCategorie ",
Int16.Parse(iDCategorieCombobox.SelectedValue.ToString()));
com.Parameters.AddWithValue("#IDTipProdus ",
Int16.Parse(iDTipProdusCombobox.SelectedValue.ToString()));
com.Parameters.Add("#IDProdusScris", SqlDbType.BigInt);
com.Parameters["#IDProdusScris"].Direction =
ParameterDirection.Output;
com.ExecuteNonQuery();
conn.Close();
Integer =
Int32.Parse(com.Parameters["#IDProdusScris"].Value.ToString());
}
Now after insert I want to update myGrid with the new record. I tried
dataGridView1.Refresh(); and dataGridView1.Update();, with no result.
Is there a way to update the grid? It looks like a simple task for VS, but I couldn't find a simple solution.
What I saw only and read on MSDN looked like some very complex operations just for a simple refresh. (It was about getting the state of the row and insert the row if the state was Added).
So is there any simple way to do this, or I have to write a method that will refresh my dataGridView every time I want (I mean to re-query my table and rebuild the dataSource)
Try like this:
dataGridView1.Refresh(); and dataGridView1.Update(); will not fetch updated records from db.
Source
You can use stored procedures are pre-complied
Create Procedure Sp_getProducts
as
BEGIN
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
END
Use this code which Uses Using Statements
using (SqlConnection conn = new SqlConnection("connection-string-here"))
{
conn.Open();
using(SqlCommand cmd=new SqlCommand("Sp_getProducts",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
da.Fill(ds);
gridView.DataSource = ds;
gridView.DataBind();
conn.Close();
}
}
Try resetting your datasource:
dataGridView1.DataSourcce = null;
dataGridView1.DataSource = [YOUR DATASET];
dataGridView1.Refresh();
dataGridView1.Update();
Can someone tell me how i can set the object reference to an instance? ....
Here, user_id is the parameter which takes a textbox value into the sql statement.
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
adap = new OracleDataAdapter("insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id,'172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt",con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20, "user_id").Value = textBox1.Text;
adap.Fill(ds,"A");
DataTable table = ds.Tables["A"];
dataGridView1.DataSource = ds.Tables["A"];
con.Dispose();
}
thanks!
edit
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
string str = "insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id, '172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt";
con.Open();
adap.InsertCommand = new OracleCommand(str, con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20).Value = textBox1.Text;
adap.InsertCommand.ExecuteNonQuery();
con.Dispose();
}
thanks everyone for your help!! i got it!
EDIT: There are multiple things wrong with your code:
You're not specifying the user_id parameter in the command, although it's in the SQL
You're trying to use the InsertCommand of the adapter even though you haven't specified any insertion SQL
You're trying to fill a dataset, but you haven't specified a query - just an insert command.
I suspect you shouldn't be using a data adapter at all. If you just need to insert some data, use:
using (var connection = new OracleConnection(...)
{
connection.Open();
string sql = "insert into banks_ben_branch_99 [... as before ...]";
using (var command = new OracleCommand(sql, conn))
{
command.Parameters.Add("user_id", OracleType.VarChar, 20)
.Value = textBox1.Text;
command.ExecuteNonQuery();
}
}
I suspect adap.InsertCommand is null in the following line:
adap.InsertCommand.Parameters.Add
On the previous line you use the following constructor:
adap = new OracleDataAdapter("insert into ...", con);
but this constructor initializes the SelectCommand, not the InsertCommand. Therefore adap.InsertCommand will still have its default value, null.
Your code then goes on to attempt to fill a DataTable using this adapter:
adap.Fill(ds,"A");
but this won't work either: you need a SelectCommand to do this.
To fill a DataSet, your code should probably look something like:
adap = new OracleDataAdapter("SELECT ... FROM ... WHERE ...", con);
adap.SelectCommand.Parameters.Add(... any parameters you need ...);
adap.Fill(ds, "A");
it is passing the break point now, no changes has been made to the oracle database tables! why is this happening.
I think you're misunderstanding how DataAdapters work.
To get data from the database into your DataTable, you need to:
Create an adapter with a SelectCommand
Call adapter.Fill to execute the SelectCommand and fill the DataTable with the result
To insert data into the database from your DataTable, you need to:
Insert a row into your DataTable with the data you want to insert
Create an adapter with an InsertCommand
Call adapter.Update to insert the data into the database.
Updating / Deleting rows in the database is similar to inserting, but uses UpdateCommand and DeleteCommand.
I think user_id is not a nullable column and it occurs when your parameter is empty. First thing is, parameter name does not match. After that, it still can happen when textbox is empty. It is better to check on client side for validation.
The parameter that you have given is null.
Sorry I know Title is really confusing but I couldn't figure out what exactly to put down.
Basically I created a Grid View which queries database and displays data. It works perfectly, no complain, however what I have right now is,
but what I want is,
Question: I am not sure how can I do this, can someone just point me out in right direction please ?
I think I will going to use nested gridviews.
Try to change your SELECT Query like below... It will you to get the Expected Result...
SQL Fiddle : http://www.sqlfiddle.com/#!3/00b5f/15
I have named the Table as Fruits
SELECT CrateTitle,CrateDescription,CrateID,
stuff(
(
SELECT ','+ [FruitTitle] FROM fruits WHERE CrateID = t.CrateID FOR XML path('')
),1,1,'') Types_of_Fruits_in_Crate
FROM (SELECT DISTINCT CrateTitle,CrateDescription,CrateID FROM fruits )t
OR
CREATE a PROC
*Place this Query in that Proc*
*Call that Proc*
*assign that Result set to GridView*
You can Assign he Stored Proc Result set to GridView by using the Below Code :
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("Your Connection String");
try
{
connection.Open();
string spName = "YOURStoredProcudureName";
SqlCommand sqlCmd = new SqlCommand(spName, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
//display the DataTable to a Data control like GridView for example
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
This is more an sql (or whatever langue your database engine uses) problem than a c# problem although one solution from c# would be (though it may be a bit of extra work) to use a html literal to draw you table at run time
the other option would be to change your sql but without more information i can't say if you could perhaps use a group by on changeID or a pivot table
I just learn how to connect C# and PostgresSQL.
I want to INSERT data from tb1(Textbox) and tb2 to database. But I don't know how to code
My previous code is SELECT from database.
this is my code
private void button1_Click(object sender, EventArgs e)
{
bool blnfound = false;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin123;Database=Login");
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM login WHERE name='" + tb1.Text + "' and password = '" + tb2.Text + "'",conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
blnfound = true;
Form2 f5 = new Form2();
f5.Show();
this.Hide();
}
if (blnfound == false)
{
MessageBox.Show("Name or password is incorrect", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
dr.Close();
conn.Close();
}
}
So please help me the code.
First off, you need to use the ExecuteNonQuery method rather than ExecuteReader since you're executing an INSERT rather than a SELECT statement. So, something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();
The ExecuteNonQuery method will also return the number of rows affected if that's important for you.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
Use:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your query. You can now refer to it in your INSERT statement with :name or :pw, for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();
Lastly, you might be interested in using an ORM rather than executing raw SQL statements. I'd check into the .NET Entity Framework or Castle Active Record, which is built on NHibernate. These libraries will allow you to query, update, create and delete data within your database without writing the actual SQL statements involved. It's a great way to get started, and will simply your code quite a bit!