c# simple update query not working - c#

SqlConnection conn = new SqlConnection(#"Data Source=SAI\SQLEXPRESS;Initial Catalog=testing;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand command = new SqlCommand();
string test = "UPDATE attend Year='2014' WHERE Id = '2'";
command = new SqlCommand(test, conn);
command.ExecuteNonQuery();
conn.Close();
Year and id are both varchar. Error is:
Incorrect syntax near 'Year'.

Should be :
UPDATE attend SET Year='2014' WHERE Id = '2'

Related

Delete and minus data at specific cell from database

I am creating a form page where I need to show data in data grid view. When the user adds any item from the grid view it should be minused from inventory and update inventory when user press add button.
The code that I am using is giving me this exception:
Additional information: Incorrect syntax near '='.
My code:
private void btnMoveItem_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True");
con2.Open();
String Query1= "DELETE FROM Inventory WHERE id = " + tbID.Text + "";
SqlCommand sqlcmd1 = new SqlCommand(Query1, con2);
sqlcmd1.ExecuteNonQuery();
SqlCommand sqlcmd = new SqlCommand("UPDATE Inventory SET Quantity = #Quantity" +"WHERE id= " + tbID, con2);
sqlcmd.Parameters.AddWithValue("#Item", this.nudQuantity.Text);
sqlcmd.ExecuteNonQuery();
con2.Close();
}
The error is that you concatenate two strings without space between.
But there are many other errors.
All user values should be a sql parameter with correct type.
nudQuantity.Text must be parsed/validated. Maybe id too.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
con2.Open();
var Query1 = "DELETE FROM Inventory WHERE id = #id";
var sqlcmd1 = new SqlCommand(Query1, con2);
sqlcmd1.Parameters.AddWithValue("#id", tbID.Text);
sqlcmd1.ExecuteNonQuery();
var sqlcmd = new SqlCommand("UPDATE Inventory SET Quantity = #Quantity WHERE id=#id", con2);
sqlcmd.Parameters.AddWithValue("#id", tbID.Text);
sqlcmd.Parameters.AddWithValue("#Quantity", int.Parse(nudQuantity.Text));
sqlcmd.ExecuteNonQuery();
}
You could also merge these two query in a single one.
This query should be more like what you need.
UPDATE Inventory SET Quantity = Quantity-#Quantity WHERE id=#id;
DELETE FROM Inventory WHERE id = #id AND Quantity <= 0;
But there are no check on product availability here. If #Quantity is greater than Quantity, then no error will be thrown.

Populate listview with data received from SQL query

I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();

Populate textbox with selected items from database

private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);

C# Error: "Fill: SelectCommand.Connection property has not been initialized."

I'm using this video to try and populate results from a DataGridView, and am receiving the above error. The below code pertains to this error - I pass values into a stored procedure, then the final SELECT returns the values in the table in the DataGridView.
SqlConnection con = new SqlConnection();
con.ConnectionString = "integrated security=SSPI;data source=SERV;" + "persist security info=False;initial catalog=DB";
con.Open();
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
// Stored Procedure
enter.CommandType = CommandType.StoredProcedure;
enter.Parameters.Add(new SqlParameter("#vvalue", SqlDbType.VarChar)).Value = Convert.ToString(txt1.Text);
enter.Parameters.Add(new SqlParameter("#dvalue", SqlDbType.Decimal)).Value = Convert.ToDecimal(txt2.Text);
enter.ExecuteNonQuery();
// DataGrid returns the SELECT
SqlDataAdapter sadapt = new SqlDataAdapter(select);
sadapt.SelectCommand = select;
DataTable dtab = new DataTable();
sadapt.Fill(dtab); // generates the error
BindingSource b = new BindingSource();
b.DataSource = dtab;
dGrid.DataSource = b;
sadapt.Update(dtab);
con.Close();
You did not pass connection object on the command. Try this instead,
SqlCommand select = new SqlCommand("SELECT * FROM Table", con);
You are passing connection object to your enter command but didnt pass the connection object to your select command
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
Use this
SqlCommand select = new SqlCommand("SELECT * FROM Table",con);
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2",Connection())// pass connection

Error while query a Textbox

This should be a simple solution but Visual Studio 2012 give me errors that say sqlCon is a field but is used like a type and the same error for Textbox1... Maybe I am missing an assembly reference or proper connection imports? I'm looking to continue this simple route.
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
sqlCon.Connection = sqlCon;
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
Open the connection
use using statements
use Try-catch block
Snippet,
string connStr = "Server=***;Port=***;Database=***;Uid=***;Pwd=***;";
string query = "SELECT count(Dues) From Students";
using(MySqlConnection sqlCon = new MySqlConnection(connStr))
{
using(MySqlCommand sqlComm = new MySqlCommand())
{
sqlComm.Connection = sqlCon;
sqlComm.CommandText = query;
try
{
sqlCon.Open();
TextBox1.Text = sqlComm.ExecuteScalar().ToString();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
//sqlCon is of type MySqlConnection which is derived from DbConnection
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
//sqlCon has no Connection property, and why are you even assigning sqlCon to that property
sqlCon.Connection = sqlCon;
//ofcourse this will fail
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
I believe what you're trying to achieve is:
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand command = new MySqlCommand ("SELECT count(Dues) From Students");
try
{
sqlCon.Open();
command.Connection = sqlCon;
TextBox1.Text = command.ExecuteScalar().ToString();
}
finally
{
sqlCon.Close();
}

Categories