Related
I'm using a a multiple query with insert and update statement together.
The problem is that if query will not be completed(for some reason e.x bad internet connection) my SQL Server table keeps rubbish.
Example of query:
SqlCommand cmd = new SqlCommand("INSERT INTO CustomerTrans (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime) SELECT " + Connection.TableName + ",' " + Connection.UserID + "', '" + Connection.Username + "',Sum(Quantity),Sum(Price),Sum(RealPrice),Sum(ExtrasPrice), Sum(Quantity * Price),Sum(Quantity * DiscountPrice),'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' from InventoryTransTemp where active=1 and TableName=" + Connection.TableName + ";update InventorytransTemp set TrnDocumentID=(select max(TrnDocumentID) from CustomerTrans where UserID='" + Connection.UserID + "'),Active=0 where TableName=" + Connection.TableName + " and Active=1", con);
cmd.ExecuteNonQuery();
Take a photo from a query which has not be completed properly look query 2989 it has NULL values. I want to avoid inserting something if query is not be completed properly.
Sorry for my previous Question it was Unclear
Try it like this:
string sql =
"INSERT INTO CustomerTrans" +
" (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime)" +
" SELECT #TableName, #UserID, #Username, Sum(Quantity), Sum(Price), Sum(RealPrice), Sum(ExtrasPrice), Sum(Quantity * Price), Sum(Quantity * DiscountPrice), current_timestamp" +
" FROM InventoryTransTemp" +
" WHERE active=1 and TableName= #TableName;\n" +
"SELECT #TranID = scope_identity;\n"
"UPDATE InventorytransTemp" +
" SET TrnDocumentID=#TranID ,Active=0" +
" WHERE TableName= #Tablename and Active=1;";
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
{
//I'm guessing at exact column types/lengths here.
// You should update this to use your exact column types and lengths.
// Don't let ADO.Net try to guess this for you.
cmd.Parameters.Add("#TableName", SqlDbType.NVarChar, 20).Value = Connection.TableName;
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Connection.UserID;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 20).Value = Connection.Username;
cmd.Parameters.Add("#TranID", SqlDbType.Int).Value = 0; //placeholder only
con.Open();
cmd.ExecuteNonQuery();
}
Note the improved formatting of the query, the use of scope_identity() to get the new identity value rather than a nested select statement that might not be atomic, that I avoided ALL uses of string concatenation to substitute data into the query, that I avoided the AddWithValue() method entirely in favor of an option that doesn't try to guess at your parameter types, and the use of using blocks to be sure the SqlClient objects are disposed properly.
The only thing I'm still concerned about is if your INSERT/SELECT operation might create more than one new record. In that case, you'll need to handle this a different way that probably involves explicit BEGIN TRANSACTION/COMMIT statements, because this code only gets one #TranID value. But in that case, the original code was broken, too.
I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay
I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}
I am unable to update my database. I have a table called Table2 and I have in it 3 columns: time, strike and vol. Please check the comments made in the line statements. thanks in advance for the help.
VolLoc = Math.Sqrt(Math.Abs(VarianceLoc));
Console.WriteLine("Local Volatility at strike " + strike1_run + " and time " + time0_run + " is: " + VolLoc + "\n"); // works perfectly at this point, I have a new value for my variable VolLoc
string StrCmd1 = "UPDATE Table2 SET (vol = #vol_value) WHERE ((time = #T0_value) AND (strike = #K1_value))"; // HERE is the problem, when I debug, the cursor steps on it normally but the database is not updated !!
OleDbCommand Cmd1 = new OleDbCommand(StrCmd1, MyConn);
Cmd1.Parameters.Add("#vol_value", OleDbType.VarChar);
Cmd1.Parameters["#vol_value"].Value = VolLoc.ToString();
Cmd1.Parameters.Add("#T0_value", OleDbType.VarChar);
Cmd1.Parameters["#T0_value"].Value = time0_run.ToString();
Cmd1.Parameters.Add("#K1_value", OleDbType.VarChar);
Cmd1.Parameters["#K1_value"].Value = strike1_run.ToString(); //the cursor steps on each of the line statements above, but the database is still not updated
Apart from the missing call to ExecuteNonQuery as stated by other, your code has another error that will show itself when your code will reach the ExecuteNonQuery method.
The word TIME is a reserved keyword in MS-Access Jet SQL.
You need to encapsulate it with square brackets [time]
So, summarizing
string StrCmd1 = "UPDATE Table2 SET vol = #vol_value WHERE " +
"([time] = #T0_value AND strike = #K1_value)";
OleDbCommand Cmd1 = new OleDbCommand(StrCmd1, MyConn);
.......
cmd1.ExecuteNonQuery();
Also, all the parameters are passed as string values. Are you sure that the corresponding fields are of the same datatype (text)
You need to call an Execute method on your OleDbCommand object.
try adding
Cmd1.ExecuteNonQuery();
I have been working on this school assignment and have gotten to a point at which I have been stuck for a few days now. My ASP.net web page is supposed to allow the user to create an account and login. However, no matter how many times I fill in the Create Account form, it doesn't seem to get added to the database.
Here is my User class, which holds the createAccount Method
public class Userr
{
//Constructor for the Account Creation method(createAccount)
public string createAccount(string strFname, string strLname, string strUname, string address, string city, string state, string phone, string zip, string email,string password)
{
string i="";
string storedProcText = ("INSERT INTO User Values('#ID," +strUname +"','"+strFname +"','"+ strLname +"','"+address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password );
ArrayList parms = null;
DataAccess dataAccess = new DataAccess();
int result = dataAccess.insertUpdateData(parms,storedProcText );
i =result.ToString();
return i;
}
public string Login(string strUsername, string strPassword)
{
DataAccess objDA = new DataAccess();
int result = objDA.LoginUser(strUsername, strPassword);
}
}
Here is my method for updating(stored in the dataAccess object/class
//Constructor for the update method
public int insertUpdateData(ArrayList items, String strProcedureName)
{
int i = 0;
string strConn = WebConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConn);
string sqlText = strProcedureName;
SqlCommand myCommand = new SqlCommand(sqlText);
myCommand.Connection = myConnection;
myCommand.CommandType = CommandType.StoredProcedure;
try
{
using (myConnection)
{
myConnection.Open();
i = myCommand.ExecuteNonQuery();
//grdData.DataSource = myReader;
// grdData.DataBind();
}
}
catch (Exception err)
{
}
return i;
}
The User table contains the follwing fields in order: ID, UserID, FirstName,LastName, Address, City, State, Zip,Phone,EmailAddress,Password
Is my SQL statement wrong, or what? I am at the end of my rope here.
So, off the bat, I see a few issues:
You set your myCommand.CommandType = CommandType.StoredProcedure but, the syntax you provided is not a stored proc. A stored proc would take a name value list of params, which is null in your case.
Lets say you didn't mean to use stored procs, in which case, your sql syntax is incorrect. You don't need the #ID parameter, unless you are passing it in (in which case, you didn't set it). It should be something like this (without knowing the structure of your table):
string storedProcText = ("INSERT INTO User Values("'" +strUname +"','"+strFname +"','"+ strLname +"','" + address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password + "'");
This is given that the values you are inserting matches your table exactly. If not, you will need to specify the table field names in your query as well, like so:
string storedProcText = ("INSERT INTO User(username, firstName, lastName, field4, field5, field6) Values("'" +strUname +"','"+strFname +"','"+ strLname +"','" + address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password + "'");
The way to do this using stored procs is this:
SqlParameter[] parameters = {
new SqlParameter("#param1", SqlDbType.NVarChar, 50),
new SqlParameter("#param2", SqlDbType.VarChar, 100),
new SqlParameter("#param3", SqlDbType.VarChar, 100),
new SqlParameter("#param4", SqlDbType.VarChar, 100),
new SqlParameter("#param5", SqlDbType.VarChar, 100),
new SqlParameter("#param6", SqlDbType.VarChar, 100)
};
parameters[0].Value = strFname;
parameters[1].Value = strLname;
.........
.........
[all the parameters you need]
You need to create a stored proc, also (obviously)
And then you call your dataaccess layer just like you are doing.
Steps for making this work:
1) Don't catch and swallow every exception. The exception will tell you what you are doing wrong here.
2) As Caspar Kleijne points out, you need to put the password in quotes.
3) As I point out, you need to add a parenthesis.
4) You should also use parameterized SQL queries
5) You probably shouldn't be passing the ID,
Here's the corrected SQL string for #2 and #3:
string storedProcText = ("INSERT INTO User Values('#ID,"
+strUname +"','"+strFname +"','"
+ strLname +"','"+address +"','"
+city +"','"+state+"','"
+zip+"','"+phone+"','"
+ email +"','"+ password
+"')" );
It'll take some refactoring to use parameterized queries, and this is a homework project, so I'll leave that as an exercise for you.
So, to start from the beginning, have you stepped through this code with the debugger and determined if it's throwing an exception or returning zero rows modified?
The most worrisome thing is the insertion of the #ID column. If this is an Identity column you shouldn't be inserting this value. If it's not, I don't see you assigning a value to it anywhere.
EDIT:
So as has been mentioned by others here you have some structural issues in you query.
I took your code and threw it in a quick project and here's what your statement looks like.
INSERT INTO User Values('#ID,UserName','FirstName','LastName','123 Some Street','SomeTown','State','54555','555-444-3333','email#email.com','ITS_A_SECRET!
Notice the end of the query. The password field isn't escaped with a closing ' and the param list is not closed with a closing bracket.
A second problem is that #Id field. Is your column in the database an identity field? (It should be) If so, just remove that.
Now, here's the real kicker. Is your table name User? That's a reserved word in SQL server so you'll get errors in your query as is. Format you query like the following and it will work.
string storedProcText = ("INSERT INTO [dbo].[User] Values('" + strUname + "','" + strFname + "','" + strLname + "','" + address + "','" + city + "','" + state + "','" + zip + "','" + phone + "','" + email + "','" + password + "')");
The other issue, as mentioned is that you have the command type set to Stored Procedure when you are not using one.
Modifying you command type to text:
myCommand.CommandType = CommandType.Text;
After I made these modifications and ran your code I ended up with a record in the database.
The most important thing to check right now is that ID field. Is it an identity column? Make sure it is and then remove it from your statement.
In the insert you are trying to insert #ID which first of all most likely would be an identity column, and unless you set IDENTITY_INSERT ON on that table, will throw an exception, second, even if it was not an identity column, you are not providing the parameter definition for the #ID parameter to the command.
Try removing #ID from the insert statement, and pass in everything else, but ID.
As a side note, your SQL Statement is prone to SQL Injection attacks since you're concatenating sql command string and values provided by user into one string. I would recommend using parameters instead the actual values and then adding parameters to the sql command later.
I cannot post everything as a comment , but can you do one thing..
put a break point and take the contents of this string
string storedProcText = ("INSERT INTO User Values('#ID," +strUname +"','"+strFname +"','"+ strLname +"','"+address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password );
and paste the value of storeProcText directly in the database and see if it can successfuly run and create a record for you.
break and debug should fix your problem
Please Comment out this statement:
myCommand.CommandType = CommandType.StoredProcedure’;
You can use a sql script directly.