This is our code to prevent the same data from being added into SQL from our C# program but only the first same data will not be added in. The remaining ones adds the same data into SQL despite our prevention in our C# program. Can somebody help us troubleshoot?
in order not to duplicate data in database usually you set some constraints to your database. By having a unique field in database you can prevent multiple addition to your db.
Currently you are also fetching data from db to check if it exist already and that creates extra cost, just manipulate the design of db so that it won't accept the same column input twice
Count the value of data that is inserted
string constr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection con = new SqlConnection(constr);
string sql1 = "SELECT COUNT (client_id) FROM client WHERE client_id = '" + txtid.Text + "' ";
SqlCommand cmd = new SqlCommand(sql1, con);
con.Open();
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp >0)
{
//show error message
}
You could check for the record you want to add, and if it doesn't exists, then add it to the table:
SqlConnection _cnt = new SqlConnection();
_cnt.ConnectionString = "Your Connection String";
SqlCommand _cmd = new SqlCommand();
_cmd.Connection = _cnt;
_cmd.CommandType = System.Data.CommandType.Text;
_cmd.CommandText = "SELECT id FROM myTable where Category=#Name";
_cmd.Parameters.Add("#Name", string);
_cmd.Parameters["#Name"].Value = newCatTitle;
_cnt.Open();
var idTemp = _cmd.ExecuteScalar();
_cmd.Dispose();
_cnt.Close();
_cnt.Dispose();
if (idTemp == null)
{
//Insert into table
}
else
{
//Message it already exists
}
Related
I am not getting, how to do insert and update of the data in C# WinForms on single button click.
private void save_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
You can add a deletion before the insertion:
private void save_Click(object sender, EventArgs e)
{
DeletePerson(id); // add this
SqlConnection cn = new SqlConnection();
...
}
public void DeletePerson(int id)
{
using(SqlConnection connection = new SqlConnection(credentials))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
cmd.ExecuteNonQuery();
}
}
Using responsible to dispose the connection.
Consider using Entity Framework or LINQ to SQL.
You are exposed to SQL injection.
First off the SQL query isn't quite right. It should look something like the following:
INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.
You should also be disposing the connection by wrapping the connection within a using statement.
using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.
You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.
To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists
SELECT 1 FROM studetail WHERE <Condition>
The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT
I'm beginner in SQL and C#. My question is: how do I check whether a row in the table exists or not? Here is my code that I am currently using:
var conn = new SqlConnection(#"Data Source");
conn.Open();
var cmd = new SqlCommand("INSERT INTO Results (PlayerName) VALUES (#PlayerName) " , conn);
cmd.Parameters.Add("#PlayerName",_playerName);
cmd.ExecuteNonQuery();
conn.Close();
I want to check if the player name exists or not, and if not, then add it to the table.
You can check it with Select statement first and then insert it if it is not exist.
Also use using statement to dispose your connection and commands automatically instead of calling Close method manually.
using(var conn = new SqlConnection(yourConnectionString))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Count(*) From Results Where PlayerName = #playerName";
cmd.Parameters.Add("#playerName", _playerName);
con.Open();
int count = (int)cmd.ExecuteScalar();
if(count == 0)
{
// It means it does not exist.
cmd.CommandText = "INSERT INTO Results(PlayerName) VALUES (#playerName)";
cmd.ExecuteNonQuery();
}
}
if not exists(select null from Results where PlayerName=#PlayerName) begin INSERT INTO Results (PlayerName) VALUES (#PlayerName) end
I have got the input to work but now I need to add to the original number every time I input to the database but I do not know how to do that, any help would be appreciated :)
String myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/coursework/Databases/runner database.accdb;"; // location of the database
OleDbConnection myConnection = new OleDbConnection(myConnectionString); // To create the database connection
OleDbCommand myCommand = new OleDbCommand(); // Use the connection for the command
myCommand.Connection = myConnection;
try
{
myConnection.Open(); // Opens the database connection
string query = "insert into tblTrainingInformation ([Username],[Calories Burnt]) values('"+GlobalUsername.username+"','" + this.txtCaloriesBurntRun.Text + "')";
OleDbCommand createCommand = new OleDbCommand(query, myConnection);
createCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to UPDATE an existing record adding a new value to your field or INSERT a new record if it is not present you need to know if your database already contains the Username.
So you need to run a SELECT query before and then decide if you need an UPDATE or an INSERT
(Access doesn't have some kind of UPSERT statement like MySql or Sql Server)
String myConnectionString = ".....";
string querySel = #"SELECT [Username],[Calories Burnt]
FROM tblTrainingInformation
WHERE [Username] = #uname";
using(OleDbConnection myConnection = new OleDbConnection(myConnectionString))
using(OleDbCommand myCommand = new OleDbCommand(querySel, myConnection))
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
using(OleDbDataReader reader = myCommand.ExecuteReader())
{
int calories = 0;
string query = "";
if(reader.Read())
{
// The record exists, read the calories and add the new value
// then execute the UPDATE
calories = Convert.ToInt32(reader["Calories Burnt"]);
calories += Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"UPDATE tblTrainingInformation
SET [Calories Burnt] = #cal
WHERE [Username] = #uname";
}
else
{
// Record doesn't exist, INSERT the new data
calories = Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"INSERT INTO tblTrainingInformation
([Calories Burnt],[Username])
VALUES(#cal, #uname)";
}
reader.Close();
myCommand.Parameters.Clear();
myCommand.Parameters.AddWithValue("#cal", calories);
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
myCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
}
}
I have made a couple of assumption here.
First I assume that UserName is the primary key in this table so you can retrieve the record using the WHERE on username value.
The second assumption is the type of the field Calories Burnt.
It should be a numeric field and, to simplify the example, I have considered it to be an integer.
These assumptions should be checked and fixed if they are not true.
Said that, notice the use of the Using Statement to correctly dispose the connection, command and reader. The removing of string concatenation from your queries is another important point. You should ALWAYS use the parameter collection to avoid Sql Injection (albeit improbable with Access) and error in parsing your values.
A final note on the order of the parameters. OleDb wants the parameter in the exact order in which the parameter placeholders appear in the query text so I have reversed the order of the INSERT to be compatible with the UPDATE command
I am working on a inventory software in which I want to access the ProductName and Product Price by Comparing it With the ProductCode, the Data I've Already Stored in Database table named ProductLog, the Data in Product Log is:
ItemNO Productode ProductName ProductPrice
1 123 lux 58
2 321 soap 68
now I want that I only enter productCode in my textbook named txtProductCode, and press tab then ProductPrice(txtProductPrice) and ProductName(txtProductName) boxes fills automatically.
The code I tried to compare the Productcode and access values is:
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
InitializeComponent();
string sql;
int productCode = 0;
productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, dbo.ProductLog.ProductName";
sql = " WHERE ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but in line productCode = Convert.ToInt32(txtProdcutCode.Text); it says Input string was not in a correct format.
Please help me out with this problem.
EDIT:
I've also tried this code :
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
string sql;
// int productCode = 0;
//productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but it says Incorrect syntax near the keyword 'WHERE'. means I am making mistake in calling database table in my query, but I am not able to find out the mistake ...
There are some issues with your SQL.
You were originally overwriting the sql variable and only ended up with a WHERE clause;
You don't have a FROM statement so the database doesn't know where you're trying to retrieve records from.
The use of AND in a SELECT statement is incorrect; you just need commas to separate the fields.
You're never selecting ProductPrice from the DB, but selecting ProductName twice!
You're not using parameterized SQL for your query, leaving your app open to SQL injection attacks.
To address this (points 1-4, I will leave point 5 for your own research),
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
Should be
sql += "SELECT ProductName, ProductPrice";
sql += " FROM dbo.ProductLog";
sql += " WHERE ProductCode = '" + txtProdcutCode.Text + "'";
Note: This answer assumes that the value of txtProductCode.Text is an integer!
EDIT: It turns out that the column, ProductCode, was a VarChar. For OP
and others reading this question, when you get SQL conversion errors
check your column datatype in SQL server and make sure it matches what
you're submitting.
That's the basics. There are many other improvements that can be made but this will get you going. Brush up on basic SQL syntax, and once you get that down, look into making this query use a parameter instead of directly placing txtProductCode.Text into your query. Good luck!
Never call InitializeComponent method twice.It's creating your form and controls and it's calling in your form's constructor.Probably when you leave your textBox it's creating again and textBox will be blank.therefore you getting that error.Delete InitializeComponent from your code and try again.
Update: your command text is wrong.here you should use +=
sql += " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
But this is not elegant and safe.Instead use paramatirezed queries like this:
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT dbo.ProductLog.ProductName,dbo.ProductLog.ProductName WHERE dbo.ProductLog.ProductCode = #pCode";
cmd.Parameters.AddWithValue("#pCode", txtProdcutCode.Text );
I have folowing code of c# in which I am making connection with access db and and using some conditions.I call a single row from db by using where clause in query.When I Logged into the page it gets data accurately.But after some time when i refresh the page it shows the folowing error
"There is No Row at position 0"
My code is is Bellow
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|OID.mdb;Persist Security Info=False;");
//OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Select * from EMAILS WHERE EMAIL= '" + GlobalData.Email + "'";
//cmd.CommandText = "Select * from EMAILS";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
String email = ds.Tables[0].Rows[0][1].ToString();
if (email == GlobalData.Email)
{
Label2.Text = GlobalData.Email;
Label1.Text = GlobalData.Name;
Label3.Text = GlobalData.LastName;
Label1.Visible = false;
Label3.Visible = false;
Label4.Text = Label1.Text + ' ' + Label3.Text;
}
}
I am querying data from DB and using where cluse with Global Variable to retrive a single row
Can Any one Please tell me that how can i Remove this issue or can i loop through the DB that evry time when user login it gets data using loop and then follow the condtion
That means your query is not returning anything and therefore when you call this line:
String email = ds.Tables[0].Rows[0][1].ToString();
You get an exception because there's no Row[0]
If you want to avoid that error do something like:
if (ds.Tables[0].Rows.Count>0)
{
String email = ds.Tables[0].Rows[0][1].ToString();
///...
}
Don't do select * ever in your code. Get used to list the exact columns you want to select from the table. For example:
select email_address from Emails where id= 5
Extra comment: Your query above is kind of pointless; it seems that you are trying to select an email address from a table using the same email address in the where clause. Why do you need to select it from the database if you already know the email? Judging by the variable name (GlobalData.Email) it seems that this is a predefined value...