First of all.. excuse me for my bad English , i hope to be understood.
I'm regullar to work with LINQ , the SQL is new for me.
i'm trying to do the next thing: i have the next method on c#:
public string niceMethod()
{
SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;");
string commandtext = "SELECT bla FROM items WHERE main = 1";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
string tDate = (string)command.ExecuteScalar();
connection.Close();
return tDate;
}
I have page for example: items.aspx?nID=144
how can i do that the SELECT command will be with querystring and that will take the value
from the "items" table by the id (nID) that show on the address ?
The table have the design for example:id, title, bla, main.
Try something like this:
int nID = int.Parse(Request.QueryString["nID"].ToString());
niceMethod(nID);
public string niceMethod(int nID)
{
using (var conn = new SqlConnection("Data Source=server;Initial Catalog=blah;Integrated Security=False;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"SELECT bla, id, title FROM items WHERE main = #nID";
cmd.Parameters.AddWithValue("#nID", nID);
string tDate = cmd.ExecuteScalar().ToString();
return tDate;
}
}
Try this:
Pay attention to the (Request.QueryString["nID"] ?? "0").ToString() it's really importent so you wont get exception when there is no query.
public string niceMethod()
{
string tDate = "";
string ID = (Request.QueryString["nID"] ?? "0").ToString(); // Get's the nID query, incase there is no query, returns 0.
using (SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;"))
{
string commandtext = "SELECT bla FROM items WHERE id=#ID"; //#ID Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
Related
It's my function to add to a table:
public int insertHistory(string title, string description, int isDone, int userId)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO History(title,description,isDone,userId) VALUES(#param1,#param2,#param3,#param4)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#param1", SqlDbType.NVarChar, 10).Value = title;
cmd.Parameters.Add("#param2", SqlDbType.NVarChar, 400).Value = description;
cmd.Parameters.Add("#param3", SqlDbType.Int).Value = isDone;
cmd.Parameters.Add("#param4", SqlDbType.Int).Value = userId;
cmd.CommandType = CommandType.Text;
s = cmd.ExecuteNonQuery();
}
}
return s;
}
What code do I need to write to remove from the table by title or something?
You have asked to delete using Title and here is how to do it
public int deleteHistory(string title)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "DELETE FROM History WHERE Title = #title)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#title", SqlDbType.NVarChar, 10).Value = title;
s = cmd.ExecuteNonQuery();
}
}
return s
}
However in this way you could end to delete more records than you want. If two or more records have the same title you will delete all records with the same title. You could mitigate this problem adding also the UserID to the where condition and the relative parameter to the parameters collection.
"DELETE FROM History WHERE Title = #title AND UserID = #uid"
So you delete only titles of a specific user, but still this is not safe. If your table has an IDENTITY column and you retrieve the values from that column when you read the records then you can pass that unique value to your query and delete specifically only one record.
"DELETE FROM History WHERE HistoryID = #hid"
as you are using SqlConnection and a plain SQL statement. You need to call a Delete statement in your code:
public void DeleteHistory(string title)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "delete from History where title= #title";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = title;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
I'm not very good but I'm trying. I think there is something I don't understand somewhere...
I'm trying to get statistique from a DB like how many row got "X". Look simple. I know the SQL statement for it. There is a lot of walkthrough around. But I don't know how to make it appear on a page.
if(!Request.QueryString["RNum"].IsEmpty() ) {
searchTerm = Request.QueryString["RNum"];
selectCommand2 = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl = #0";
}
var Count = db.QueryValue(selectCommand2, searchTerm);
With a submit button to send the query how can I make it appear on a page?
just try this
searchTerm = Request.QueryString["RNum"];
string sqlSelect = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
// Set SqlDbType based on your DB column Data-Type
sqlCommand.Parameters.Add("#NoEmpl", System.Data.SqlDbType.Varcahr);
sqlCommand.Parameters["#NoEmpl"].Value = searchTerm ;
OR
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#NoEmpl", searchTerm ));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
//read here
}
}
I am trying to use If statement for two query. If query one = query 2
string select = "Select ProfileId from Project_list Where ProjectId = #ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
object Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
object User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult == User_profileResult)
{
addFollowerButton.Visible = true;
}
This is the code I have so, but is not working.
Error 18 The name 'Project_listResult' does not exist in the current
Error 19 The name 'User_profileResult' does not exist in the current
You have to define both values outside, so that are in scope to use them. Right now you are define both values in using, so those are just under the scope of only under and not available outside that, so you are getting that error.
A simple suggestion is that avoid use of keywords those are part of different language, as you are using select as variable name. This help to increase readability and increase confusion.
Refer
object Project_listResult = null;
object User_profileResult = null;
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
Project_listResult = myCommand.ExecuteScalar();
}
string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
User_profileResult= myCommand.ExecuteScalar();
}
if (Project_listResult.Equals(User_profileResult))
{
addFollowerButton.Visible = true;
}
If I'm understand you you're trying to compare the objects. So you've got to try
if (Project_listResult.Equals(User_profileResult))
addFollowerButton.Visible = true;
http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx
I am a new ASP.NET developer and I am developing a web-based application in which there is a menu bar that has many options. Some of these options will be displayed only to the Admin. There is a logic behind the system to check whether the user is an admin or not. If yes, the options will be displayed. I wrote the method but I have a sql injectiom and I want to remove it.
For your information, I have the following database design:
Users table: NetID, Name, Title
Admins table: ID, NetID
Here's the C# method:
private bool isAdmin(string username)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = '" + NetID + "')";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["ID"].Equals(1))
return true;
return false;
}
}
}
I tried to change it by doing the changing the third line to:
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
But I got the following error and I don't know why:
Must declare the scalar variable "#NetID".
Could you please help me in solving this?
**UPDATE:
After updating the code to the following:
private bool isAdmin(string username)
{
string NetID = username;
string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["NetID"] == username)
return true;
return false;
}
}
}
I got the following error:
Incorrect syntax near ')'.
How to fix this problem?
You need to pass a value for your #NetID parameter:
cmd.Parameters.AddWithValue("#NetID", NetID);
Try this
private bool isAdmin(string username)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["ID"].Equals(1))
return true;
return false;
}
}
}
If you use NetId as parameter in the IsAdmin method than it would help
private bool isAdmin(string NetID)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
string value = cmd.ExecuteScalar().tostring();
if (value != null)
return true;
else
return false;
}
}
}
Its better to use
cmd.Parameters.Add("#netid",SqlBdType.Int).Value=NetID;
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.