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
Related
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
}
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query
My code is to update a record if it already exists in database else insert as a new record.
My code is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
MyConnection.Open();
String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("", TextBox3.Text);
using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
MyCmd1.ExecuteNonQuery();
}
else
{
// set the SQL string
String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
"VALUES (?,?,?)";
// Create the Command and set its properties
OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
objCmd.Parameters.AddWithValue("", HiddenField4.Value);
objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
objCmd.Parameters.AddWithValue("", TextBox3.Text);
// execute the command
objCmd.ExecuteNonQuery();
}
}
}
I am getting the error as:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009',' &' at line 1
The datatype for fields in table temp_save are:
fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
Please help me to resolve my error.
order is a reserved word. For a complete list of Reserved Words, please review this document.
You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)
INSERT INTO temp_save (fil_no,`order`,orderdate)....
i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql
String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";
The title is probably confusing, but basically i want to do something along the lines of this,
string sql = "select dataset1 from dbo.ste where project = 'whatever' and date = '11/30/10'";
SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
if(cmd "is not null")
{
//do this string
}
else
{
//do this one
}
obviously cmd "is not null") is not real, but i think you guys might get the point.
I don't understand why everyone is trying to use ExecuteNonQuery or ExecuteScalar when the query in the question is a SELECT statement. If it was a stored procedure call that took care of the logic of INSERT versus UPDATE based on the existence of a value, the ExecuteScalar would make sense because you can return whatever single value you want from a stored procedure.
However, given the structure of the question, I'm leaning towards this as the answer.
// Automatically dispose the connection when done
using(SqlConnection connection = new SqlConnection(sqlConnection.ConnectionString)) {
try {
connection.Open();
// query to check whether value exists
string sql = #"SELECT dataset1
FROM dbo.ste
WHERE project = 'whatever'
AND date = '2010-11-30'";
// create the command object
using(SqlCommand command = new SqlCommand(sql, connection)) {
using(SqlDataReader reader = command.ExecuteReader()) {
// if the result set is not NULL
if(reader.HasRows) {
// update the existing value + the value from the text file
}
else {
// insert a value from a text file
}
}
}
}
finally {
// always close connection when done
if(connection.State != ConnectionState.Closed) {
connection.Close();
}
}
}
You can change the query to use WHERE EXISTS if you don't want to stream back full matches, but from the sounds of it, you would only have at most 1 match anyways.
If you want to check if there is any matching records, you can count them:
string sql = "select count(*) from dbo.ste where project = 'whatever' and date = '11/30/10'";
To get the result you use the ExecuteScalar method:
int cnt = Convert.ToInt32(cmd.ExecuteScalar());
It looks like you want to do var result = cmd.ExecuteScalar(); and then compare if (result == DBNull.Value).
ExecuteNonQuery returns the number of rows affected (if certain options are not selected) as an integer. So, you can either verify the count is equal to (or greater than) some success condition or execute scalar and return a value from your query to indicate success.
Try this:
string sql = "select COUNT(dataset1) from dbo.ste where project = 'whatever' and date = '11/30/10'";
SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if(count != 0)
{
//do this string
}
else
{
//do this one
}
I have a table named t_Student in Microsoft SQL Server 2005 database. In that table there are three columns named student_regiNo, student_Name, student_Email.
I'm using following code segment to retrieve "student_Name". But instead of showing "student_Name" it shows "System.Data.SqlClient.SqlDataReader". Whats the problem?
private void GetDatabaseConnection()
{
string connectionString = #"server=RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; database = StudentCourseInformation";
connection = new SqlConnection(connectionString);
connection.Open();
}
public string GateStudentName(string selectedStudentRegiNo)
{
GetDatabaseConnection();
string selectedStudentQuery = #"SELECT student_Name FROM t_Student WHERE (
student_regiNo =
'" +selectedStudentRegiNo+ #"'
)";
SqlCommand command = new SqlCommand(selectedStudentQuery, connection);
SqlDataReader reader = command.ExecuteReader();
string selectedStudentName = Convert.ToString(reader);
return selectedStudentName;
}
Use
return (string)command.ExecuteScalar();
as far as you have to return "the first column of the first row in the result set returned by the query" (from MSDN)
Also use parametrized query:
var command = new connection.CreateCommand()
command.CommandText = "SELECT student_Name FROM t_Student WHERE student_regiNo = #number";
command.Parameters.AddWithValue(#number, selectedStudentRegiNo);
ExecuteReader returns a SqlDataReader. You need to use the SqlDataReader API to read the data from it. Don't forget that a query can return multiple rows, with multiple columns in each row. For example:
while (reader.Read())
{
string name = reader.GetString(0);
Console.WriteLine("Read name: {0}", name);
}
Further note that you should use a parameterized query rather than including the ID directly into the SQL - otherwise you leave yourself open to SQL injection attacks. See the docs for SqlCommand.Parameters for more information.
Finally, you should use using statements for the SqlConnection, SqlCommand and SqlDataReader so that you dispose of them appropriately. Otherwise you're going to leak database connections.
if (reader.Read())
{
string selectedStudentName = reader.GetString(0);
}
SqlCommand command = new SqlCommand(selectedStudentQuery, connection);
SqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
return reader["student_Name"];
}
return "not exist";