Sending information to a specific column in a database C# - c#

I Have a table with 3 columns, when an alarm goes off, I want the time of that alarm to be stored in the 2nd column of the table(AlarmActivated). Then if that alarm is turned off, it stores that time in the same row of the table but in column 3. This is my code:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString());
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.ExecuteReader();
Con.Close();
This is executed when a value goes to 0.

ExecuteReader returns some data. Since you wanna insert, you need to use ExecuteNonQuery instead.
And do not store your DateTime values as a string. Change your column type to datetime2 and pass your DateTime.Now value directly to your parameterized query. Please read Bad habits to kick : choosing the wrong data type
Also using DateTime.Now can be ambigious. Read Matt's article The case against DateTime.Now
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
Since you insert only one column, other two columns will be null or their default value.
string ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30"
using(var Con = new SqlConnection(ConStr))
using(var Command = Con.CreateCommand())
{
Command.CommandText = "INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarm)";
Command.Parameters.Add("#alarm", SqlDbType.DateTime2).Value = DateTime.Now;
Con.Open();
Command.ExecuteNonQuery();
}

The problem is in
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString())
It has to be
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (" + DateTime.Now.ToString() + ")";

wrong function is used, use this function: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx ExecuteNonQuery

First, your string for your insert is badly formed. You need to put the parentheses inside quotes:
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES('" + DateTime.Now.ToString() +"')";
Secondly, you need to use parameterized queries instead, because building your SQL like this is a bad habit to get into and can lead to SQL injection breaches:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarmTime)";
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.Parameters.AddWithValue("#alarmTime", DateTime.Now);
Command.ExecuteNonQuery();
Con.Close();
Finally, only the column AlarmActivated will be set with a value. The other two columns will be populated by their default value. If you want the other two columns to have a value other than their default, you need to specify them and provide a value.

You can create 2 stored procedures in SQL, one will insert row and return ##SCOPE_IDENTITY (you can store it in list<>), which you will use as a param for updating procedure.
Try to avoid using SQL statemensts in code, to prevent code injection.

Related

how to Insert large string into CLOB column of Oracle in C#?

Does anyone know how to insert large string value into Oracle CLOB column?
I only can insert short string into CLOB column....
Can you help me find out what change I have to make from this code?
using Oracle.DataAccess.Client; //from Oracle.DataAccess.dll
using System.Data;
string _strConn =
"Data Source=(DESCRIPTION="
+ "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=LOCALHOST)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));"
+ "User Id=userID;Password=userID;";
// Connect To Oracle
OracleConnection conn = new OracleConnection(_strConn);
conn.Open();
// Create Instance to command
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
// Define SQL command
cmd.CommandText = "insert into practice_clob values ('a', 'aaa')"; //This works
//This does not work with the error message, "string literal too long"
//cmd.CommandText = "insert into practice_clob values ('a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')";
cmd.ExecuteNonQuery();
conn.Close();
This is my table from Oracle...
create table practice_clob(
str varchar2(100),
clob_value clob
);
Can anyone edit the code to insert large string value into CLOB column of Oracle?
Pretty much do what Oracle tells you:
"ORA-01704: string literal too long
Cause: The string literal is longer than 4000 characters.
Action: Use a string literal of at most 4000 characters. Longer values may only be entered using bind variables."
So, just use a parameter instead. As a bonus, you'll also avoid SQL injection.

Use Variable In SQL String

How can I add a variable to my SQL string and run it against the server successfully? I want to run this statement through my C#
protected void RunSQLQuery(string salesman, string connectionString)
{
SqlConnection cnn;
SqlCommand cmd;
StringBuilder sql = new StringBuilder();
SqlDataReader reader;
cnn = new SqlConnection(connectionString);
sql = new StringBuilder();
sql.Append("update database ");
sql.Append("set shippdate = GetDate() ");
sql.Append("where salesman = "' + salesman + "'");
sql.Append("and managerapproval is not null ");
cnn.Open();
cmd = new SqlCommand(sql.ToString(), cnn);
reader = cmd.ExecuteReader();
reader.Close();
cmd.Dispose();
cnn.Close
}
This presents multiple compile errors underlining my +salesman+ code. The errors are:
Only assignment, call, increment, decrement, and new object
expressions can be used as a statement
; expected
) expected
Too many characters in character literal Newline in constant
You are not adding the string object that salesman refers, you are adding salesman as a string literal.
Just add it as a parameter like;
var cmd = new SqlCommand("update database set shippdate = GetDate() where salesman = #salesman");
cmd.Parameters.Add("#salesman", salesman);
...
And use ExecuteNonQuery to execute your command, not SqlDataReader. This SqlDataReader is for return some data.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
As a full example;
protected void RunSQLQuery(string salesman, string connectionString)
{
using(var cnn = new SqlConnection(connectionString))
using(var cmd = cnn.CreateCommand())
{
cmd.CommandText = #"update database set shippdate = GetDate()
where salesman = #salesman";
// I assume your column is nvarchar
cmd.Parameters.Add("#salesman", SqlDbType.NVarChar).Value = salesman;
cnn.Open();
cmd.ExecuteNonQuery();
}
}
For myself, I always prefer to use SqlParameterCollection.Add(string, SqlDbType, Int32) overload to specify my parameter type and it's size but since you never mentioned your salesman column type, I couldn't post this in my example.
As you can also see from the syntax highlighting, the compile errors are caused because you did not escape the quotes properly in sql.Append("where salesman = "' + salesman + "'");.
As a side note, you should never insert strings into sql queries without first validating them, or you are open to sql injection, e.g. if i pass "''; drop table database;" as salesman parameter. It is better to use SqlParameter.
I would suggest using the AddWithValue method from your sql command combined with the UPPER function to make it case insensitive:
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = "UPDATE database SET shippdate = GetDate() WHERE UPPER(salesman) = UPPER(#salesMan)";
cmd.Parameters.AddWithValue("#salesMan", salesman);
if (cnn.State.Equals(ConnectionState.Closed))
{
cnn.Open();
}
cmd.ExecuteNonQuery();
cnn.Close();
As mentioned in above answers, yes, writing queries in this way is not a good way to do it. But still if you want to do it that way only, you will have to change:
sql.Append("where salesman = "' + salesman + "'");
to
sql.Append("where salesman = '" + salesman + "'");

Incorrect Syntax near "*"

I'm having problems with my code. I haven't used SQL services at anytime, so its kinda tricky to figure out what's the problem. The main problem is what it says on the title, i get incorrect Syntax when i try to Read, Update or Delete data from SQL database.
Here is the code:
string Connection2 = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AuthMyRegistery\AuthMyRegistery\Data.mdf;Integrated Security=True;User Instance=True";
string Query = "delete from * where idWorkerInfo='" + this.WorkerIdTextBox.Text + "';";
SqlConnection Conn2 = new SqlConnection(Connection2);
SqlCommand Command2 = new SqlCommand(Query, Conn2);
SqlDataReader Reader2;
Conn2.Open();
Reader2 = Command2.ExecuteReader();
MessageBox.Show("Data Deleted");
while (Reader2.Read())
{
}
Conn2.Close();
Issue is here, no table name defined
delete from * where idWorkerInfo=
Should be
Delete From TableName where idWorkerInfo=
'*' isn't a valid target for a delete statement, what table do you want to delete from?
The syntax should be something like
delete from MyTable where idWorkerInfo='abc'
You need to specify the name of table instead of a wildcard.
The basic syntax of the DELETE statement is the following (see the full documentation in MSDN - DELETE (Transact-SQL)):
DELETE FROM table_name
WHERE some_column=some_value;
Moreover, you should not be creating your SQL query using string concatenation (never ever use this in production), as this makes you vulnerable to SQL injection attacks.
Instead, you should be using a parameterized query so that all user input gets properly escaped:
var cmd = new SqlCommand("DELETE FROM MyTable WHERE idWorkerInfo=#id", conn2);
cmd.Parameters.AddWithValue("#id", WorkerIdTextBox.Text);
cmd.ExecuteNonQuery();
The query itself is incorrect.
Consider this:
delete from * where idWorkerInfo='Sth'
You need to replace * with an actual table name.
There is no * in delete ... The syntax of delete is as follows
DELETE FROM table_name
WHERE some_column = some_value;

Updating Values with C# in SQL Table

I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx

Is this query to retrieve data from database correct?

I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.

Categories

Resources