Related
private void btnadd_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql = ("Insert into tbl_books values NameOfBook = #book, Author =#author, Publisher=#publisher,YearPublished=#year,Category=#category,ISBN=#isbn");
MySqlCommand sda = new MySqlCommand(sql,conn);
sda.Parameters.AddWithValue("#book", txtbook.Text);
sda.Parameters.AddWithValue("#author", txtauthor.Text);
sda.Parameters.AddWithValue("#publisher", txtpublisher.Text);
sda.Parameters.AddWithValue("#year", txtyear.Text);
sda.Parameters.AddWithValue("#category", cmbcategory.Text);
sda.Parameters.AddWithValue("#isbn", txtisbn.Text);
sda.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Item has been added");
showlv("Select * from tbl_books", lvbooks);
}
catch (Exception)
{
MessageBox.Show("Cannot Add Item");
}
}
What is wrong with the code? It keeps on going into the catch block.
Your SQL is messed up. Try:
try
{
conn.Open();
string sql = "Insert into tbl_books (NameOfBook,Author,Publisher,YearPublished,Category,ISBN) values (#book,#author,#publisher,#year,#category,#isbn)";
MySqlCommand sda = new MySqlCommand(sql,conn);
sda.Parameters.AddWithValue("#book", txtbook.Text);
sda.Parameters.AddWithValue("#author", txtauthor.Text);
sda.Parameters.AddWithValue("#publisher", txtpublisher.Text);
sda.Parameters.AddWithValue("#year", txtyear.Text);
sda.Parameters.AddWithValue("#category", cmbcategory.Text);
sda.Parameters.AddWithValue("#isbn", txtisbn.Text);
sda.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Item has been added");
showlv("Select * from tbl_books", lvbooks);
}
And THANK YOU for taking the time to learn about parameterization. In-line SQL is the ripest tool for hackers and the most embarrassing and easy-to-fix security hole there is!
NOTE: you may want to bring your conn into the TRY block and wrap it in a USING statement to save resources:
using(SqlConnection conn = getMyConnection())
{
conn.Open();
//blah
conn.Close();
}
I'm updating and deleting these tables by stored procedure...
Update query:
ALTER PROCEDURE [dbo].[IssueUpdate]
(#BookID int,
#BookName nvarchar(50),
#DateIssue datetime,
#ReturnDate datetime,
#PersonID int)
AS
UPDATE tblIssue
SET [BookID] = #BookID ,
[BookName] = #BookName,
[DateIssue] = #DateIssue,
[ReturnDate] = #ReturnDate,
[PersonID] = #PersonID
WHERE BookID = #BookID
Update query:
ALTER PROCEDURE [dbo].[Issuedelete]
AS
DELETE FROM tblIssue
C# code to delete from tblIssue:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("Issuedelete", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
C# code to update tblIssue:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BookID", SqlDbType.Int);
cmd.Parameters.Add("#BookName", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#DateIssue", SqlDbType.DateTime);
cmd.Parameters.Add("#ReturnDate", SqlDbType.DateTime);
cmd.Parameters.Add("#PersonID", SqlDbType.Int);
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
After compiling, I get an error.
String input was not in a correct format
I tried other ways by changing the parameters with OleDB and SqlDbType... But it's not deleting and updating records... And also having same problem when I'm updating and deleting into tblReturn... Please, help me??? :(
for your update code, Like DonBoitnott mentioned, you need to give values as well:
private void btnupdate_Click(object sender, EventArgs e)
{
try
{
string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("IssueUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BookID", SqlDbType.Int).Value = "Enter Value here";
cmd.Parameters.Add("#BookName", SqlDbType.NVarChar, 50).Value = "Enter Value here";
cmd.Parameters.Add("#DateIssue", SqlDbType.DateTime).Value = "Enter Value here";
cmd.Parameters.Add("#ReturnDate", SqlDbType.DateTime).Value = "Enter Value here";
cmd.Parameters.Add("#PersonID", SqlDbType.Int).Value = "Enter Value here";
cmd.ExecuteNonQuery();
con.Close();
storedproc();
}
catch (Exception ex)
{
Console.WriteLine("SqlError" + ex);
}
}
To me it seems that because you don`t add values as pointed out by amit dayama, the SqlDbType, will act up.
if you could try setting the value of #DateIssue and #ReturnDate to DateTime.Now,
and exclude the rest of the parameters for now.
for the rest of the values:
int wil always have a value (o), but DateTime can throw an exception. for varchar i don`t know exactly.
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
i have an error as which is on the button click event, as its shows me an error message on this line:
com.EndExecuteNonQuery();
message text: Error 2 No overload for method 'EndExecuteNonQuery' takes 0 arguments
Thank you for your support
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string cmdStr = "Select count(*) from UserInfo where UID = '" + UsrNme.Text + "'";
SqlCommand com = new SqlCommand(cmdStr, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
chkusrnamlbl.Visible = true;
}
conn.Close();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string insertquery = "insert into UserInfo (UID,FN,LN,Password,Email,CountID,State,City) Values (#username,#firstn,#lastn,#passbox,#email1,#country,#state,#city)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#username", UsrNme.Text);
com.Parameters.AddWithValue("#firstn", fnbox.Text);
com.Parameters.AddWithValue("#lastn", lnamebox.Text);
com.Parameters.AddWithValue("#passbox", passtxtbx1.Text);
com.Parameters.AddWithValue("#email1", emailbox.Text);
com.Parameters.AddWithValue("#country", DrDncoundrlst.SelectedItem.ToString());
com.Parameters.AddWithValue("#state", DropDownListSwestate.SelectedItem.ToString());
com.Parameters.AddWithValue("#city", citytxtbox.Text);
com.EndExecuteNonQuery();
Response.Redirect("User panel.aspx");
conn.Close();
}
catch(Exception ex) {
Response.Write("Error:" + ex.ToString());
}
EndExecuteNonQuery requires an IAsyncResult parameter as mentioned here in MSDN.
Also, is this just a code snippet? Because I think you would want to use com.ExecuteNonQuery() instead. EndExecuteNonQuery is the end pair for asynchronously executing SQL statements.
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}