data won't insert in database via asp.net - asp.net

Im trying to insert some text that a Label has, and it wont insert it for some reason.
this is my code :
cmd = new SqlCommand(sqlquery1, conn);
cmd.Parameters.AddWithValue("Status", UserNameOrGuest.Text);
ErrorLabel.Text = "Movie rental succeeded!";
the sqlquery is : string sqlquery1 = "INSERT INTO Movies (Status) VALUES (#Status)";
Thanks for the help

You created the SqlCommand object but you are not executing the command to perform insert operation. use cmd.ExecuteNonQuery() to execute the command.
cmd = new SqlCommand(sqlquery1, conn);
cmd.Parameters.AddWithValue("Status", UserNameOrGuest.Text);
cmd.ExecuteNonQuery();
ErrorLabel.Text = "Movie rental succeeded!";
Check example here : SqlCommand.ExecuteNonQuery Method and SqlCommand.ExecuteScalar Method
create a SqlCommand and then executes it using ExecuteNonQuery/ExecuteScaler.

Is this your entire code? you seem to miss a call which executes the query?
cmd.ExecuteNonQuery();

You forgot a statment?
cmd.ExecuteNonQuery();

Related

asp.net insert data into DB

con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Hey guys, been working on this website for a while, but I get an error when putting data into the database saying
Incorrect syntax near ')'.
With other stuff that I'm putting same way it works and this does not.
You should really really REALLY use parametrized queries to avoid SQL injection (and to boost performance; and avoid issues with type conversions etc.)
So I would recommend using code something like this:
// define your *parametrized* SQL statement
string insertStmt = "INSERT INTO dbo.YourTable(Col1, Col2, Col3) VALUES(#Val1, #Val2, #Val3);";
// put SqlConnection and SqlCommand into "using" blocks to ensure proper disposal
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// set the parameters to the values you need
cmd.Parameters.AddWithValue("#Val1", "Some String here");
cmd.Parameters.AddWithValue("#Val2", 42);
cmd.Parameters.AddWithValue("#Val3", DateTime.Today.AddDays(-7));
// open connection, execute query, close connection right away
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
Points to remember:
ALWAYS use parametrized queries - do NOT concatenate together your SQL statements!
put the SqlConnection and SqlCommand into using(...) { ... } blocks to ensure proper disposal
always explicitly define the list of columns you want to use in a SELECT and also an INSERT statement
open connection as late as possible, execute query, close connection again right away
That will do the job but I strongly advice using Parameters.
con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout values ('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Instead of the code above you'd better to use
cmd2 = new SqlCommand("insert into dailyWorkout values (#val1, #val2, #val3,#val4,#val5,#val6)", con);
cmd2.Parameters.AddWithValue("#val1",RadioButton1.Text);
cmd2.Parameters.AddWithValue("#val2",RadioButton2.Text);
cmd2.Parameters.AddWithValue("#val3",RadioButton3.Text);
cmd2.Parameters.AddWithValue("#val4",RadioButton4.Text);
cmd2.Parameters.AddWithValue("#val5",RadioButton5.Text);
cmd2.Parameters.AddWithValue("#val6",Label1.Text)
cmd2.ExecuteNonQuery();
Ok its already been mentioned, don't inject parameters like that.
But if you must, the problem is that your final sql string looks like:
insert into dailyWorkout('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
when it should be
insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6)
values('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
But you should really consider:
var sqlCmd = new SqlCommand("insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6) values(#v1, #v2, #v3, #v4, #v5, #v6)", default(SqlConnection));
sqlCmd.Parameters.Add("#v1", SqlDbType.NVarChar).Value = RadioButton1.Text;
sqlCmd.Parameters.Add("#v2", SqlDbType.NVarChar).Value = RadioButton2.Text;
sqlCmd.Parameters.Add("#v3", SqlDbType.NVarChar).Value = RadioButton3.Text;
sqlCmd.Parameters.Add("#v4", SqlDbType.NVarChar).Value = RadioButton4.Text;
sqlCmd.Parameters.Add("#v5", SqlDbType.NVarChar).Value = RadioButton5.Text;
sqlCmd.Parameters.Add("#v6", SqlDbType.NVarChar).Value = Label1.Text;
sqlCmd.ExecuteNonQuery();

Accessing sql server temporary table from asp.net

What I am missing to get data from temporary table. This is showing error like Invalid object name #emp. Please help me
I am using Asp.net.
Dim sqlcmd = New SqlCommand("select * into #emp from employees", conn)
sqlcmd.ExecuteNonQuery()
sqlcmd = New SqlCommand("select * from #emp", conn)
Dim dr As SqlDataReader = sqlcmd.ExecuteReader
See Above query is working fine and data is going into temporary table. but it is not selecting again through second one query.
Thanks
Try to use Global Temporary table instead of Local Temporary tabel like.. ##emp
or
You can just use a stored procedure which has all the SQL statement you want to execute and return your desired recordset.

Insert into SQL Server table gives me nothing

Very frustrating one... I have tried many combinations of ', " and so on but my insert command just refreshing the page.
What am I doing wrong?
Simple two text fields form with button. Under button I have this:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
con.Open();
string cmdStr = "INSERT INTO specyfik(speNazwa, speIlosc) values ('" + speNazwa.Text + "', '" + speIlosc.Text + "')";
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
con.Close();
Zero errors while compiling and when testing, it seems like refreshed page. Nothing appears in db.
Don't you need to call insertCmd.ExecuteNonQuery() ?
...
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
int row_affected = insertCmd.ExecuteNonQuery();
...
You need to execute your SqlCommand:
insertCmd.ExecuteNonQuery();
Also, you should look into parameterizing that query:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Will you like to make more improvements in your code using stored Proc and improvemnet in your code behind file ? Take a look at this answer...
https://stackoverflow.com/a/9595501/1209450

how to run two queries using the code snippet below?

How to Run two Update Sql Queries using this Sql Snippet ?
The code mentioned below is updating values only in one table .... i want to update data in two different tables using the code mentioned below :
can anybody reedit this code ?
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String =
"UPDATE a1_ticket
SET Ticket_no =#ticketNo,
BANK = #bank,
PAID = #paid,
BID = #bid
WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Create a Stored Procedure that updates the two tables and execute it using a StoredProcedure Command...
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateTheTwoTables";
....
Modify the SQL statement to update the two tables.
Using a Stored Procedure is the cleanest way code wise. If you don't feel comfortable doing it like that, I'm sure you can do it like this:
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
//
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a2_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
It's a sketch of what I'm trying to say, you may want to change a few things here and there, but the point is you can just update your two tables one after the other. It's not possible in one update statement afaik.
you can also use
Dim sql As String = # "Query for first update;
Query for second update;";
Well as you havent said anything about the second table, or the data you're sending it. I havent put this through the compiler to verify it, but the concept I'd suggest would be
You could do:
void UpdateDB(String sql, String[][] params)
{
Try
{
SqlConnection conn = New SqlConnection(constr);
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sql;
for(int i=0; i<params.length; i++)
{
cmd.Parameters.AddWithValue(params[i,0] params[i,1]);
}
cmd.ExecuteNonQuery();
}
Catch (Exception ex)
{
Response.Write(ex.Message);
}
}
eg send the SQL and the parameters to the function and have it do all the work..

MySQL / ASP.NET Stored Procedures

Hopefully this is not a ServerFault question...
I'm working forward on migrating a project from storing data in XML Serialization to a MySQL database. I'm using the example provided me from a previous question answered yesterday.
Connecting using phpMyAdmin and MySQL Workbench I've created a Stored Procedure called 'sprocOrderSelectSingleItem'. It seems to work well with MySQL for all I can tell. When I run the SHOW CREATE PROCEDURE sprocOrderSelectSingleItem it returns the following:
CREATE DEFINER=username#% PROCEDURE sprocOrderSelectSingleItem(IN orderID INTEGER)
BEGIN SELECT * FROM tblOrders WHERE ID=orderID; END
My cooperative ASP.NET code goes something like this:
public static Order GetItem(int ID)
{
Order objOrder = null;
using (OdbcConnection objConnection = new OdbcConnection(Utils.ApplicationConfiguration.ConnectionString))
{
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.AddWithValue("orderID", ID);
objConnection.Open();
using (OdbcDataReader objReader = objCommand.ExecuteReader())
{
if (objReader.Read())
{
objOrder = FillDataRecord(objReader);
}
objReader.Close();
}
objConnection.Close();
}
return objOrder;
}
When I view the page I get the following error message:
ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.77]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 'sprocOrderSelectSingleItem' at line 1
Really not catching on to what could be missing or going wrong. Are there any additional tests I should/could be running to confirm things are working on the MySQL side? Am I missing a step to pass the Stored Procedure call correctly in ASP.NET? The code breaks at the line of:
using (OdbcDataReader objReader = objCommand.ExecuteReader())
Replacing the line of
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
with this instead
OdbcCommand objCommand = new OdbcCommand("SELECT * FROM tblOrders WHERE ID=" + ID + ";", objConnection);
and everything works as expected.
Thanks for any help you guys can provide.
Your can run an execute on sprocOrderSelectSingleItem in Mysql directly with the ID parameter.
It will show that your StoredProc run correctly.
Here is a sample code in C# that call a stored proc.
OdbcCommand salesCMD = new OdbcCommand("{ CALL SalesByCategory(?) }", nwindConn);
salesCMD.CommandType = CommandType.StoredProcedure;
OdbcParameter myParm = salesCMD.Parameters.Add("#CategoryName", OdbcType.VarChar, 15);
myParm.Value = "Beverages";
OdbcDataReader myReader = salesCMD.ExecuteReader();
Look at the "Call" in the OdbcCommand and the "?" for the parameter that is later supplied with a value.
Can you try something like below:
OdbcCommand cmd = new OdbcCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "{call LoadCustCliOrders(?,?,?,?)}";
cmd.Parameters.Add("CUST_ID",OdbcType.Int);
cmd.Parameters.Add("CLIENT_ID",OdbcType.Int);
cmd.Parameters.Add("DATE_FROM",OdbcType.Date);
cmd.Parameters.Add("DATE_TO",OdbcType.Date);
...
cmd.Parameters["CUST_ID"].Value = _CustId;
cmd.Parameters["CLIENT_ID"].Value = _ClientId;
cmd.Parameters["DATE_FROM"].Value = _DateFrom;
cmd.Parameters["DATE_TO"].Value = _DateTo;
cmd.ExecuteReader
Are you sure that you are using the same username or user with the same access privileges.
I think you need to add the word "CALL" before the stored proc.
It should be CALL sprocOrderSelectSingleItem and try.

Resources