Writing values to sql database - sql

I am trying to write three variables into a database table. The code I have is:
sqlCmd.CommandText = "INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(StudentNumber.ToString() , Time.ToString() , Total.ToString())" + dbConnection;
sqlCmd.ExecuteNonQuery();
sqlTran.Commit();
dbconnection is the name of the connection. It does not do anything. It is in a try-catch but goes straight to catch.
Thanks in advance.

You should
avoid concatenating together your SQL statement - avoid SQL injection attacks! Use parametrized queries instead!
use using blocks for your SqlConnection and SqlCommand objects
Try something like this:
string _connString = "........";
string queryStmt =
"INSERT INTO dbo.PortfolioValues(StudentNumber, TimeStamp, PortfolioValue) " +
"VALUES(#StudentNumber, #TimeStamp, #TotalValue)";
using(SqlConnection _con = new SqlConnection(_connString))
using(SqlCommad _cmd = new SQlCommand(queryStmt, _con))
{
// create paramters and set values
_cmd.Parameters.Add("#StudentNumber", SqlDbType.Int).Value = StudentNumber;
// do the same for the other two parameters
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch(Exception exc)
{
// handle exception
}
}

StudentNumber.ToString() cannot be contained in a query! It's java code not sql...

//Am asuming you are using C# and the System.Data.SqlClient
//here is how you might do what you want
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
//so that you use it this way:
String query = String.Formart("INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(\"{0}\",\"{1}\",\"{2}\")",StudentNumber.ToString() , Time.ToString() , Total.ToString());
String connectionString = "your connection string";
CreateCommand(query,connectionString);

Related

Store date and time in sql server 2012 using c#

i want to store date and time in SQL Server 2012 using asp.net but generate some error "Conversion failed when converting date and/or time from character string."
protected void btn Submit_Click(object sender, EventArgs e)
{
lbldate.Text = Convert.ToDateTime(this.txtdate.Text).ToString("dd/MM/yyyy");
lbltime.Text = Convert.ToDateTime(this.txttime.Text).ToLongTimeString();
TimeSpan time = new TimeSpan();
time.ToString();
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-O6SE533;Initial Catalog=Datertime;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
SqlCommand cmd = new SqlCommand("insert date,time into DateTimedemo values('" +txtdate.Text + "','"+txttime.Text+"')", con);
con.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Write("success");
}
else
{
Response.Write("failed");
}
}
Use parameterized SQL instead of building the SQL dynamically. This avoids SQL injection attacks and string formatting differences, as well as making the code clearer.
Additionally, I believe both "date" and "time" are keywords in T-SQL, so you should put them in square brackets when using them as field names.
You should attempt to perform as few string conversions as possible. Without knowing exactly what your web page looks like it's hard to know exactly how you want to parse the text, but assuming that Convert.ToDateTime is working for you (sounds worryingly culture-dependent to me) you'd have code like this:
protected void btn Submit_Click(object sender, EventArgs e)
{
// TODO: Ideally use a date/time picker etc.
DateTime date = Convert.ToDateTime(txtdate.Text);
DateTime time = Convert.ToDateTime(txttime.Text);
// You'd probably want to get the connection string dynamically, or at least have
// it in a shared constant somewhere.
using (var con = new SqlConnection(connectionString))
{
string sql = "insert [date], [time] into DateTimeDemo values (#date, #time)";
using (var cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("#date", SqlDbType.Date).Value = date;
cmd.Parameters.Add("#time", SqlDbType.Time).Value = time.TimeOfDay;
int rows = cmd.ExecuteNonQuery();
string message = rows > 0 ? "success" : "failed";
Response.Write(message);
}
}
}
I've guessed at what SQL types you're using. If these are meant to represent a combined date and time, you should at least consider using a single field of type DateTime2 instead of separate fields.

Like and = operater is not working together in signal query

I am using sap.net web form. In this web form i have a text and a button. user enter name or id and hit search button. Searching with id is working fine but with name it is not working.
What i am missing here help me out please.
String Status = "Active";
String BDstring = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(BDstring))
{
try
{
String query = "SELECT * from Driver where(Name LIKE '%' + #search + '%' OR DriverID = #search) AND Status = 'Active'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#search", SearchTextBox.Text);
conn.Open();
SqlDataReader SDR = cmd.ExecuteReader();
DataTable DT = new DataTable();
if (SDR.HasRows)
{
DT.Load(SDR);
GridView.DataSource = DT;
GridView.DataBind();
}
}
catch (SqlException exe)
{
throw exe;
}
}
}
The code is generating an exception. The fact that you're unaware of this indicates that you have "error handling" somewhere in your system that is, in fact "error hiding". Remove empty catch blocks, or pointless catch blocks such as the one in your question that just destroys some information in the exception and re-throws it. Those aren't helping you.
The actual problem is that the DriverID column is int and your parameter is varchar. So long as the varchar contains a string that can be converted to a number (which is the direction that the conversion happens in due to precedence), the query is well-formed.
As soon as the parameter contains a string that cannot be implicitly converted to a number, SQL Server generates an error that .NET turns into an exception.
For your LIKE variant, you're forcing a conversion in the opposite direction (numeric -> varchar) since LIKE only operates on strings. That conversion will always succeed, but it means that you're performing textual comparisons rather than numeric, and also means there's no possible index usage here.
I'd suggest that you change your C# code to attempt a int.TryParse on the input text and then uses two separate parameters to pass strings and (optionally) their numeric equivalent to SQL Server. Then use the appropriate parameters in your query for each comparison.
Something like:
String Status = "Active";
String BDstring = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(BDstring))
{
String query = "SELECT * from Driver where(Name LIKE '%' + #search + '%' OR " +
"DriverID = #driverId) AND Status = 'Active'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("#search", SqlDbType.VarChar,50).Value = SearchTextBox.Text;
cmd.Parameters.Add("#driverId", SqlDbType.Int);
int driverId;
if(int.TryParse(SearchTextBox.Text, out driverId))
{
cmd.Parameters["#driverId"].Value = driverId;
}
conn.Open();
SqlDataReader SDR = cmd.ExecuteReader();
DataTable DT = new DataTable();
if (SDR.HasRows)
{
DT.Load(SDR);
GridView.DataSource = DT;
GridView.DataBind();
}
}
"SELECT * from Driver where (Name LIKE '%" + #search + "%'
OR DriverID = '" + #search + "' ) AND Status = 'Active'";
how about this?

string not accepting " 's " while writing to database

Hello everyone i am creating a settings page for another application using mvc4. In the settings page:
1.It contains two text areas wherein the user can type anything.
2.After typing if the user clicks submit button, the text he has written is saved in a sql database.
3.The main application will read that data from the database and display it.
Here are my respective codes:
Model:
public string PartnerInfo1 { get; set; }
public string PartnerInfo2 { get; set; }
Controller:
[HttpPost]
public ActionResult Index(AddDetailModel model)
{
pinfo1 = model.PartnerInfo1;
pinfo2 = model.PartnerInfo2;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sample"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
cmd.ExecuteNonQuery();
return RedirectToAction("Index");
}
and in the view:
#Html.TextAreaFor(m => m.PartnerInfo1)
#Html.TextAreaFor(m => m.PartnerInfo2)
in the database, the corresponding table contains two columns PartnerInfo1,PartnerInfo2 and their datatype is nvarchar(max).
My problem is when i type apostrophe in text area it gives me error.For example if i type "world's" it gives error on clicking submit button.
This is the error:
Incorrect syntax near 's'.
Unclosed quotation mark after the character string ''.
Please suggest what i can do to avoid this.Any help would be appreciated.
Never do that - it's unsafe and allow to make sql injection:
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
Instead of that use the following parameters syntax:
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1=#pinfo1, PartnerInfo2=#pinfo2 where [PartnerID]='cs'", con);
cmd.Parameters.AddWithValue("#pinfo1", pinfo1);
cmd.Parameters.AddWithValue("#pinfo2", pinfo2);
Your method expose your query to sql injection attacks. You are much better using a parameterised query which will sort out your ' issue as well.
string connString = ConfigurationManager.ConnectionStrings["Sample"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("Update dbo.Partner_Design " +
"Set PartnerInfo1=#pinfo1, " +
"PartnerInfo2=#pinfo2 " +
"Where [PartnerID]=#partnerId", con);
cmd.Parameters.AddWithValue("#pinfo1", model.PartnerInfo1);
cmd.Parameters.AddWithValue("#pinfo2", model.PartnerInfo2);
cmd.Parameters.AddWithValue("#partnerId", "cs");
con.Open();
cmd.ExecuteNonQuery();
}
You can escape the single quote by prefixing it with another single quote, which would require doing a replace on your string before you add it to the query i.e.:
pinfo1 = pinfo1.Replace("'", "''");
pinfo2 = pinfo2.Replace("'", "''");
SqlCommand cmd = new SqlCommand("update dbo.Partner_Design set PartnerInfo1='" + pinfo1 + "',PartnerInfo2='" + pinfo2 + "' where [PartnerID]='cs'", con);
I would however strongly advise against this and take the advice of the other responses that instead use parameterised SQL which is much more secure. Note also that this solution will only solve your single quotes problem, and will still cause issues with other special characters that need escaping individually. As such whilst this should answer your question, the solutions proposed by SÅ‚awomir Rosiek and Kaf are much more comprehensive, much safer, and are best practice.
The method you are using leaves you open to SQL injection attacks.

SQL - OleDbCommand not changing Sql Parameter

Below is the code for my Select * Function - It WORKS well and does everything great until i change the SQL string from Select * From Company to
query = "Select * From #1";
and then do the following
query = "Select * From #1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("#1", SQLTables.Company);
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
The DBMS keeps sending back "Query incomplete" - I assume The Command variable is sending the string query through without changing the Parameter from #1 to Company
Here is a piece of code (mine) where this does work. This is an insert statement rather that a select - Correct me if i am wrong but should it not also work with the SELECT aswell
private void MainActionsInsert(string Action, bool Checked)
{
OleDbCommand Command = new OleDbCommand("INSERT INTO MainActions Values (ID, Action, BoolValue)", DataBaseConnection);
//Add Parameters
Command.Parameters.AddWithValue("ID", GenerateID());
Command.Parameters.AddWithValue("Action", Action);
Command.Parameters.AddWithValue("BoolValue",Checked);
//Add Command
MainActionsAdapter.InsertCommand = Command;
//Execute Agains DataBase
Command.ExecuteNonQuery();
//Accept Changes
}
`
OLEdb doesn't recognize named parameters. You must use ? in the query text.
However, you also can't use dynamic table names with parameterized queries, so even using a ? will not help.
You need to use full dynamic SQL, though that can open you up to SQL Injection. Make sure you read the full article I linked.
OleDbCommand Does accept Parameterized SQL just not in the From Clause - It Has to be either in a WHERE clause or something like that. Like you said it Worked with the insert function because it expects "parameters" there. For example this will work
query = "Select * From Company Where #param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
Funny though that it doesn't work for the Select part though

ExecuteReader returns no results, when inspected query does

Consider the following code:
StringBuilder textResults = new StringBuilder();
using(SqlConnection connection = new SqlConnection(GetEntityConnectionString()))
{
connection.Open();
m.Connection = connection;
SqlDataReader results = m.ExecuteReader();
while (results.Read())
{
textResults.Append(String.Format("{0}", results[0]));
}
}
I used Activity Monitor within Sql Server Mgmt Studio on the database to inspect the exact query that was being sent. I then copied that query text to a query editor window within SSMS, and the query returned the expected results. However, SqlDataReader results is always empty, indicating "The enumeration returned no results."
My suspicion is that somehow the results are not being returned correctly, which makes me think there's something wrong with the code above, and not the query itself being passed.
Is there anything that would cause this in the code above? Or something I've overlooked?
EDIT:
Here is the query as indicated by the SQLCommand object:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('#param1','#param2','#param3')
ORDER BY StandardId
Here is the query as it appears in Activity Monitor:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('ABC-001-0','ABC-001-0.1','ABC-001-0')
ORDER BY StandardId
The query is working against a single view.
When I ran the second query against the database, it returned 3 rows.
The SqlDataReader indicates 0 rows.
try to use Sqldata adapter instead of sqldatreader.
StringBuilder textResults = new StringBuilder();
using (var conn = new SqlConnection(GetEntityConnectionString())))
{
using (
var cmd = new SqlCommand(
"SELECT DISTINCT StandardId,Number" +
"FROM vStandardsAndRequirements " +
"WHERE StandardId IN (#param1,#param2,#param3)" +
"ORDER BY StandardIdl"
, conn))
{
var dSet = new DataSet();
var dt = new Datatable();
var da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#param1", SqlDbType.VarChar, 50).Value = "ABC-001-0";
cmd.Parameters.Add("#param2", SqlDbType.VarChar, 50).Value = "ABC-001-0.1";
cmd.Parameters.Add("#param3", SqlDbType.VarChar, 50).Value = "ABC-001-0";
try
{
da.Fill(dSet);
dt = dSet.Tables[0];
foreach(Datarow a in dt.Rows)
{
textResults.Append(a["StandardId"].tostring()).AppendLine();
}
Messabox.Show(textResults.tostring);
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Regards.
Are you sure it is
WHERE StandardId IN ('#param1','#param2','#param3')
instead of this?
WHERE StandardId IN (#param1,#param2,#param3)
Parameters should not be quoted, not in the SQLCommand object.
Very nice behavior I've observed
I looked for errors in code:
... dr = command.ExecuteReader() ... If dr.Read Then ...
and found that 'dr.Read' works fine, but...
when I mouseover on 'dr', to lookup for data, return values disappeared !
Check your connection string and make sure you are not connecting as a user instance.
http://msdn.microsoft.com/en-us/library/ms254504.aspx