I'm working on access database using C#, want an SQL statement to select all information based on a desired date. for example today.
"SELECT * from mytable where mytable.dates == DateTime.Today()";
If I understand the question right and you want to make a call to the SQL Server, you can use SQLCommand and parameters.
var sqlCommand = new SqlCommand();
sqlCommand.CommandText = "SELECT * from mytable where mytable.dates= #DateAdded";
sqlCommand.Parameters.AddWithValue("#DateAdded", DateTime.Today);
Related
I have a SqlDataReader, which needs to read certain values out of my database. The SqlCommand which selects these values looks like this:
SqlCommand myCommand = new SqlCommand("SELECT * FROM dbo.Confronting_Value", valueConnection);
Each entry in the database consists of "Attacker", "Defender" and "Value". All 3 contain integer values.
For example
Attacker: "665", Defender: "443", Value: "3".
There may be multiple entries where the "Attacker" has the value "665".
Now, SELECT WHERE Attacker = 665 would be simple, but I have a variable Black.ID. I want to select all entries where the Attacker has the same value as Black.ID. How do I do that?
Not sure if I understand you correctly - but just adding a parameter to the query might work:
SqlCommand myCommand = new SqlCommand(#"SELECT *
FROM dbo.Confronting_Value
WHERE Attacker = #Value", valueConnection);
// add parameter and set its value to "Black.ID"
myCommand.Parameters.Add("#Value", SqlDbType.Int).Value = Black.ID;
and then from here on, run the code you already have. This will select all rows where Attacker has the same value as your Black.ID value.
Sorry, what is Black.ID? A variable in your code? A column of another table in the database?
In the first case add a Where clause to your command like this:
"SELECT * from dbo.Confronting_Value WHERE Attacker=" + Black.ID
or better
SqlCommand myCommand = new SqlCommand("SELECT * FROM dbo.Confronting_Value WHERE Attacker = #param1", valueConnection);
myCommand.Parameters.Add("#param1", SqlDbType.Int);
myCommand.Parameters["#param1"].Value = Black.ID;
Hope this can help you.
I have do some calculation in C# and i want insert that value to MySql database. Example totalPrice= Price1+Price2; I want pass the totalPrice into my table. How to do that?
You need to use an INSERT statement. It's probably best to use parameterized queries rather than just an INSERT command.
MySqlCommand command = new MySqlCommand();
string sql = "INSERT INTO YourTable (TotalPrice) VALUES (#TotalPrice)";
command.Parameters.AddWithValue("#TotalPrice", totalPrice);
Then remember to execute your query. command.ExecuteNonQuery();
If you are using EntityFramework...
yourTable obj = new yourTable();
obj.name = "name";
obj.created = DateTime.Now;
etc.......
ctx.yourTable.Add(obj);
ctx.SaveChanges();
or
ctx.Database.ExecuteSqlCommand("Insert intoy YourTable values etc..");
Can I use where condition in Insert statement????
I have coded like this, its showng me an error call MySQLException was unhandled, 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 'WHERE RegistrationID='3'' at line 1. My code:-
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO registration(DueAmount) VALUES ('"+textBox5.Text + "') WHERE RegistrationID='"+textBox2.Text+"'",connection);
You're mixing 2 different statements.
An UPDATE statement updates an existing row in your table.
An INSERT statement adds a new row in your table.
I think you want to use an UPDATE statement and modify an existing row.
MySqlCommand cmd1 = new MySqlCommand("
UPDATE Registration Set DueAmount= '"+textBox5.Text
+ "' WHERE RegistrationID='"+textBox2.Text+"'",connection);
The correct syntax of INSERT doesn't have WHERE clause. I think you want UPDATE instead of INSERT,
UPDATE registration
SET DueAmount = 'txt5'
WHERE RegistrationID = 'txt2'
the only way you can use WHERE in SELECT is when you are using INSERT INTO....SELECT statement.
one more thing, since you are using ADO.NET, make sure that you parameterized your query to avoid SQL Injection, and use USING statement.
string query = "UPDATE registration
SET DueAmount = #dateAmount
WHERE RegistrationID = #RegID"
using (MySqlCommand cmd1 = new MySqlCommand(query,connection))
{
cmd1.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#dateAmount", textBox5.Text);
cmd.Parameters.AddWithValue("#RegID", textBox2.Text);
// other codes
}
INSERT with WHERE doesn't make sense. INSERT always inserts a new row. You might be looking for REPLACE INTO which does a insert if that record doesnt exist or an update if it does based on its primary key.
INSERT puts a new line to database. You can not put a new line WHERE sth is sth. But you can UPDATE it. Hope this helps.
You need to use an UPDATE statement.
tHS SYNTAX IS SIMILAR: "UPDATE registration SET DueAmount = '" + textBox5.Text + "' WHERE RegistrationID='"+textBox2.Text+"'"
You can try with Update
var query = "UPDATE Registration SET DueAmount= $Paremeter1 WHERE RegistrationID = $Paremeter2";
var cmd1 = new MySqlCommand(query, connection);
cmd1 .Parameters.AddWithValue("$Paremeter1", textBox5.Text);
cmd1 .Parameters.AddWithValue("$Paremeter2", textBox2.Text);
Currently I am working on a project regarding C# and SQL and I have a problem regarding the SELECT function and I cannot find any solutions on-line.
The scenario is regard searching query from C# through SQL server and display the results in a Data Grid View at C#.
I'm using Visual Studio 2008 and SQL Server Studio 2008.
Before starting the project I just did a quick Windows form from Visual studio and just did a datagridview, 2 text boxes and a Search Button.
At SQL Server I have a a database with a table DVD and I want to search, from this Windows form with the DVD ID and Name.
I started with the DVD ID and implemented this code :
private void btnView_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
DataTable t = new DataTable();
string sqlString = "SELECT * From DVD where Id ='" + txtID.Text+ "'";
SqlDataAdapter dt = new SqlDataAdapter(sqlString, c);
dt.Fill(t);
dtgv1.DataSource = t;
}
and it worked :)
Then I changed the code to
string sqlString = "SELECT * From DVD where Name ='" + txtName.Text+ "'";
so that I can search with Name of the DVD but when I started the program and searched with the Name it just showed a blank database
Also is there any way that I can change the code so that I can either search with the ID or with the Name ?
Thanks for your help and time
Thoughts:
Make sure txtName.Text has a value
Try SQL select using Enterprise Manager, Toad, or some other query tool. What do you get?
Try using LIKE as example below
Worst case, maybe check the Collation for the Table, perhaps its set to 'Case Sensitive' text matching.
Both ID and Name:
SELECT * FROM DVD
WHERE Id=[ID Value]
OR Name LIKE '%[Name Value]%'
Or you could use SQLCommand with parameters like this:
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
string queryString = "SELECT * From DVD where Id = #id";
var paramId = new SqlParameter("id", SqlDbType.VarChar);
var query = new SqlCommand(queryString, c);
query.Parameters.Add(paramId);
If you really want to use an SQLDataAdapter, you can set the select command to the one I wrote above. Otherwise, you can use a dataReader and iterate through the results.
Also, using parameters like this makes your query easier to read and makes it safer to SQL injections. It should always be considered.
Edit1: If you want to search with either the Id or the Name, you can just make 2 parameters, and put an OR between the 2, and maybe use the keyword like instead of = in your query. If the values can be null, you may want to build your query dynamically, depending on the values that are not null.
I'm creating an assembly in C# for MS SQL 2005. This assembly creates a stored procedure and runs a dynamic query based on parameters passed into the stored procedure.
Is there a simple function in C# to prevent SQL injection?
For example
string myQuery = "SELECT * FROM dbo.MyTable WHERE lastName = '" + injectionCheck(arg1) + "'";
This question was answered for the standard query... but in situations where there is no way around building a truely dynamic query what can I use in C# for injection checking?
For example, these probably wont work:
using #dbName;
SELECT * FROM #table
OPEN SYMMETRIC KEY #keyName
etc
Use bound parameters:
SqlCommand cmd = new SqlCommand(myQuery, conn);
cmd.Parameters.Add("#lastname", SqlDbType.NVarChar, 10, lastName);
Use parameters ....
(This has been posted often already)
string myQuery = "SELECT * FROM myTable WHERE lastname = #p_name";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myQuery;
cmd.Parameters.Add ("#p_name", SqlDbType.Varchar).Value = "melp";