C# SQL query not returning anything - c#

I have the public DataTable here and the code looks right, but its not returning anything, the OrderID is correct, the query itself is correct, its not returning anything...can anyone tell me why?
public DataTable get_OrderTransaction_Master_ByOrderID(Int64 orderID)
{
cn = new SqlConnection(objCommon.IpcConnectionString);
cn.Open();
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = " + orderID;
SqlCommand queryCommand = new SqlCommand(query, cn);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(queryCommandReader);
cn.Close();
return dataTable;
}

Caveat:This is a guess based on incomplete information:
Try this: Change query string and add the line to add the parameter.
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = #OrderId";
SqlCommand queryCommand = new SqlCommand(query, cn);
queryCommand.Parameters.AddWithValue("#OrderId", orderID);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
Explanation: Not only will this prevent SQL Injection, it will automatically assure that the OrderId is handled correctly.
You didn't specify what the data type is for the OrderId in the database. I'm guessing it may be non-numeric. (guid or varchar - I've seen databases that use nun-numeric IDs, so it's not inconceiveable.) If it's non-numeric you may be missing the quotes areound the value.
Example:
Where Id = 1
is NOT the same as
Where Id= '1'
Using a parameterized query will automagically fix this for you.

Related

System.Data.SqlClient.SqlException: "Invalid column name 'e'." | Error with Database

Im using Database Data for my Project and when I type a letter in Textbox1, the application crashes with the error:
System.Data.SqlClient.SqlException: "Invalid column name 'e'."
Database name is Table with "Id" and "altitudes"
Id is a varchar and altitudes is a nchar.
Thats how I want it to work:
Typing a Name in name.Text, search for the name in the database and paste the assigned altitude in altitude.Text.
Altitudes are numbers, Names are Letters in the database.
Where's the error in my code? (Data Source is on purpose blank)
{
String source = #"Data Source=";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID ="+char.Parse(name.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
altitude.Text = (dr["altitudes"].ToString());
}
con.Close();
}
You should never concatenate inputs to create SQL. It is horribly brittle, and susceptible to SQL injection, and i18n/l10n problems (formatting of values). Lots of bad things.
The solution should always be: parameters.
For example:
const string sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = #id";
using SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
cmd.Parameters.AddWithValue("#id", name.Text);
// Etc
Or more easily with a tool like Dapper:
var alt = con.QuerySingleOrDefault<string>(
"SELECT altitudes FROM [Table] WHERE ID = #id",
new { id = name.Text });

I Want to get id from select query in C# but every time i run the program, The query returns me "-1" [duplicate]

This question already has answers here:
Return value of a select statement
(7 answers)
Closed 5 years ago.
I am trying To get ID against selected name in Drop Down list by using select query but it always returns the value "-1" instead of relevant result.
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname = '" + pr + "'";
cmd2.CommandText = "Select Pid From Provinces where Pname = '" + prov.Text + "'";
int pid = cmd2.ExecuteNonQuery();
You need to use ExecuteScalar instead of ExecuteNonQuery
int pid = Convert.ToInt32(cmd2.ExecuteScalar());
For more details please refer Link
The reason is that ExecuteNonQuery doesn't return the database value when using a Select command - It returns a return code for success or failure.
If you want to read the database value, use the following code. Note that I used an SqlParameter instead of your parameter concatenation, which can cause SQL injections and is a poor practice:
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname=#pr";
cmd2.Parameters.Add(new SqlParameter("pr", pr));
int result = Convert.ToInt32(cmd2.ExecuteScalar());
Alternativly, you can use fill a DataTable with multiple results:
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select Pid From Provinces where Pname=#pr";
cmd2.Parameters.Add(new SqlParameter("pr", pr));
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter(cmd2);
// Create a new datatable which will hold the query results:
DataTable dt = new DataTable();
Connection.Open();
// Fill a datatable with the query results:
adp.Fill(dt);
Connection.Close();
Let me add few notes for you before answer the question, You should aware about the usage of ExecuteNonQuery, and why other peoples refer ExecuteScalar for you. here is the difference you have to note.
ExecuteNonQuery() does not return data at all: only the number of rows affected by an insert, update, or delete
ExecuteScalar() only returns the value from the first column of the first row of your query.
There is few more things I want to remind you, As a developer we won't give the key to hackers through SqlInjection, for that we should use parameterization like the following:
using(SqlCommand cmdSql = con.CreateCommand())
{
cmdSql.CommandType = CommandType.Text;
cmdSql.CommandText = "Select Pid From Provinces where Pname =#Pname";
cmdSql.Parameters.Add("#Pname ", SqlDbType.VarChar).Value= prov.Text;
int pid = Convert.ToInt32(cmdSql.ExecuteScalar());
}

Get last ID from select query in C# WPF

I would like to get last selected person ID.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
SqlCommand cmd = new SqlCommand(personID, con);
SqlDataReader reader = cmd.ExecuteReader();
var lastSelectedSingleClientPhoneId = reader.GetDecimal(0);
But unfortunately it did not work. I already tried to get int16, int32 and int64. When i use INSERT I can get the ID using the following select:
SELECT SCOPE_IDENTITY();
Insert command below:
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName);SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
var lastInsertedPersontId = reader.GetDecimal(0);'
This should return all Persons beginning with 'XYZ' in the Persons database table.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
using(var cmd = new SqlCommand(personID, con))
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
}
I appreciate you're looking for a type to call GetXXX, but you can easily extend this pseudo-code to determine the appropriate type.
You can try combining the two SQL statements as one CommandText value then use ExecuteScalar to return the last inserted ID
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName); SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
int personID = (int)cmd.ExecuteScalar();
/// ... convert integer value to a string or do something
You can also try this SQL statement as an alternative:
SELECT TOP 1 PersonID FROM Persons ORDER BY PersonID DESC;

DataAdapter.Fill syntax error

So,
Trying to write a very simple method to update a single column in a database. I keep getting a runtime error of "Syntax Error" near the commented line below
public void SaveStatus(string id, string step)
{
// assuming that there is only one matching student ID
connect = new SqlConnection(connectionString);
connect.Open();
dataSet = new DataSet();
string command = "SELECT * FROM tblSubmissions WHERE Id = " + id;
dataAdapter = new SqlDataAdapter(command, connect);
dataAdapter.Fill(dataSet, "tblSubmissions"); // syntax error near here
dataSet.Tables[0].Rows[0]["StatusID"] = step;
dataAdapter.Update(dataSet, "tblSubmissions");
dataAdapter.Dispose();
connect.Close();
connect.Dispose();
}
Hoping someone can point out the obvious problem I'm missing
The query should be "SELECT * FROM tblSubmissions WHERE Id = 'id_value' - you're missing the quotes around the id value.
Use a parametrised query instead of string concatenation to fix your problem and get rid of the SQL injection issue:
SqlCommand cmd = new SqlCommand("SELECT * FROM tblSubmissions WHERE Id = #id" , connect);
cmd.Parameters.Add("#id", SqlDbType.UniqueIdentifier);
cmd.Parameters["#id"].Value = id;

System.ArgumentException: The table type parameter must have a valid type name

I am trying to pass in a user defined table type into a query in C#.
the type is defined with 2 columns (org and sub org)
this is what my code looks like:
DataSet ds = new DataSet();
try
{
DataTable FilteredOrgSubOrg = new DataTable("OrgSubOrgValueType");
FilteredOrgSubOrg.Columns.Add("org", typeof(string));
FilteredOrgSubOrg.Columns.Add("subOrg", typeof(string));
FilteredOrgSubOrg.Rows.Add(org, orgsub);
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"select * from myTable ex where year = #year' and qtr = #qtr" +
" and EXISTS(SELECT 1 FROM #OrgSubOrg tt WHERE ex.org like tt.org" +
" AND ex.orgsub = tt.suborg )"+
" order by ex.org,year, qtr DESC";
// 2. set the command object so it knows
// to execute a stored procedure
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#OrgSubOrg", FilteredOrgSubOrg));
cmd.Parameters.Add(new SqlParameter("#year", year));
cmd.Parameters.Add(new SqlParameter("#qtr", qtr));
conn.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = cmd;
sqlDA.Fill(ds);
}
}
am i passing the parameters in incorrectly?
when i do it in SQL server like so:
declare #OrgSubOrg OrgSubOrgValueType
insert into #OrgSubOrg values ('05%','00000000')
insert into #OrgSubOrg values ('03%','00000000')
------------ complete -----------------------------------
select * from myTable ex
where
year = '2013' and qtr = '1'
and EXISTS(
SELECT 1
FROM #OrgSubOrg tt
WHERE ex.org like tt.org
AND ex.orgsub = tt.suborg )
order by ex.org,year, qtr DESC
everything works like it should.
i also tried passing it in like so:
SqlParameter p = cmd.Parameters.Add(new SqlParameter("#OrgSubOrg", SqlDbType.Structured));
p.Value = FilteredOrgSubOrg;
but am getting the same error
The table type parameter '#OrgSubOrg' must have a valid type name.
could it be that i can't pass it to a SQL command, i have similar code in another place, that works great with a stored procedure...?
Set mapping to your type in SqlServer using TypeName property that: Gets or sets the type name for a table-valued parameter, that has to fix .
p.TypeName = "dbo.MyType";
Check as well Table-Valued Parameters post
Note that this may also happen when you're executing a stored procedure and you don't have the SqlCommand.CommandType set to CommandType.StoredProcedure, as such:
using (SqlCommand cmd = new SqlCommand("StoredProcName", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
You can get this error also when you wanna pass table params into stored procedure. There is happen if you use entity famework Context.Database.SqlQuery(). You must necessary set TypeName property for your table params.
SqlParameter codesParam = new SqlParameter(CODES_PARAM, SqlDbType.Structured);
SqlParameter factoriesParam = new SqlParameter(FACTORIES_PARAM, SqlDbType.Structured);
codesParam.Value = tbCodes;
codesParam.TypeName = "[dbo].[MES_CodesType]";
factoriesParam.Value = tbfactories;
factoriesParam.TypeName = "[dbo].[MES_FactoriesType]";
var list = _context.Database.SqlQuery<MESGoodsRemain>($"{SP_NAME} {CODES_PARAM}, {FACTORIES_PARAM}"
, new SqlParameter[] {
codesParam,
factoriesParam
}
).ToList();

Categories

Resources