SqlDataAdapter, SqlCommand dropping the leading numbers from string - c#

I am trying to execute a SQL statement with a where clause which looks like
string s2 = "Select * from idtyfile where oysterid=" + id ;
SqlCommand da2 = new SqlCommand(s2, con); or
SqlAdapter da2 = new SqlAdapter(s2, con);
Both of these are failing when I am trying to execute them
da2.ExecuteReader();
the data in ID looks like
ID
43PCOU5T
ZP6RAEJ0
For some reason both of these queries are failing on these kind of data.

You are missing the single quotes in your select command which is what is making your original SELECT fail. However I would like to note that you should always parameterize and encapsulate your SqlCommand / SqlConnection in a using statement. The following would be a cleaner more secure way to solve your problem.
string s2 = "Select * from idtyfile where oysterid=#id";
DataTable myDataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = new SqlCommand(s2, conn))
{
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
myDataTable.Load(cmd.ExecuteReader());
}
For some educational resources, you should look at the following links.
MSDN Reference for the using keyword
MSDN Reference for SqlCommand -- Look at the Parameters property.

Related

ASP.NET getting data from SQL Server

I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.
I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
           
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
          
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
    Name.Text = da.GetValue(1).ToString();
}
            
con.Close();
Better solution is to execute the sql statement through Parameterized value.
The details of that process is given below:
using (SqlConnection con = new SqlConnection(live_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Query", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmpId", employeeId);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
var ds = new DataSet();
da.Fill(ds);
string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
Name.Text =name;
};
}
}
As mentioned above in comments, you have lot of issues.
you should use using with the connection to dispose of them.
You should use parameterized queries to avoid SQL injection.
Put your code in try catch so that you can easily identify the root cause of the issue.
Define the connection string in config file three than defining in the c# code.
You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.
You can use ExecuteScalar, it’s used when you are expecting single value.
And first make sure that textbox has the expected value when you are calling this query.
As noted, use paramters, and BETTER use STRONG typed paramters.
And no need to use a dataset, this is a single table - so use a datatable.
thus:
string strSQL =
#"select * from ProfessionalDetails where EmpId= #ID";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
con.Open();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = EmployeeID.Text;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
if (rstData.Rows.Count > 0)
Name.Text = rstData.Rows[0]["Name"].ToString();
}
}

The specified method is not supported

I'm working on a program that shows in a chart in asp.net two columns of a table, so I made a connection to my database (which is correct), the problem is in the metudo (Chart1.DataBindTable) that does not Is working And gives the following error: The specified method is not supported.
I was very grateful if anyone helped me.
The code:
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas] GO", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
Chart1.DataBindTable(rdr, " Consumo_Medio_Real");
Remove that GO from your SQL statement. Your SQL statement should looks like
SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]
Well you are getting error cause the specified column name has space in it as can be seen below
Chart1.DataBindTable(rdr, " Consumo_Medio_Real");
^... Here
It should rather be like below cause the column name represents the X-Axis
Chart1.DataBindTable(rdr, "Consumo_Medio_Real");
See below MSDN link for an example
https://msdn.microsoft.com/en-us/library/dd456766.aspx
Try without "GO"
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
//Add datatable...
System.Data.DataTable dt = new DataTable();
dt.Load(rdr);
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
And try dumping the data into some objet that implement ienumerable... and pass that as the parameter to .DataBindTable()
look the definition here (the SqlDataReader does not implement IEnumerable)
hope this help!

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

Dynamically passing a value inside a query?

I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}

C# - Web Site - SQL Select Statement

I want to use a select statement to find if there is a record that already exists. I've put the code below but it throws an error at the dReader = comm.ExecuteReader(); and i'm unsure why. Any help?
string connString = "Data Source=KIMMY-MSI\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
comm.Connection.Open();
dReader = comm.ExecuteReader();
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
The error:
Invalid Column Name (whatever I input)
It seems to be looking for a column named what I input rather than looking for the actual data.
Change your == to =. That is invalid SQL as it is.
Also if txtID.Text is non-numeric then it needs to be in single quotes. You should not be constructing your SQL like this, instead use a parameter:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #CustomerID";
comm.Parameters.AddWithValue("CustomerID", txtID.Text);
More Info
C# using statement
SQL reference
SQL injection (why you should parameterize your queries)
It looks like your command has an issue:
SELECT * FROM Customers WHERE CustomerID == 1
In SQL you don't need to use the == operator to ensure something is equal to another.
Try:
SELECT * FROM Customers WHERE CustomerID = 1
In addition, you might want to read up about SQL Injection, the way you are binding the value is directly from a textbox value. This has a huge security hole which could lead to arbitrary sql command execution.
Change this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
To this line:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #id";
comm.Parameters.AddWithValue("id", int.Parse(txtID.Text));
Assuming that your customer id is int on the database.
The equals operator in SQL is just a single =.
Also, you really shouldn't be concatenating SQL queries like that, you are just opening yourself up to SQL Injection attack. So change it to be like this:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = #CustomerId";
comm.Parameters.AddWithValue("#CustomerId", txtID.Text);
See Stop SQL Injection Attacks Before They Stop You on MSDN.
You are using invalid SQL. You name to change "==" to "=".
You should also consider wrapping your IDisposable objects in using statements so that unmanaged objects are properly disposed of and connections are properly closed.
Finally, think about using parameters in your SQL, instead of concatenating strings, to avoid SQL injection attacks:
string connString = #"Data Source=KIMMY-MSI\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
string sql = "SELECT * FROM Customers WHERE CustomerID = #CustomerID";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand(sql, conn))
{
comm.Connection.Open();
comm.Parameters.AddWithValue("#CustomerID", txtID.Text);
using (SqlDataReader dReader = comm.ExecuteReader())
{
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
}
}

Categories