string query = "SELECT date(EDate,'utc'),Tag,Valuex,Note from collections where Account_Number = '1010011' AND Edate >= '2021-01-01'";
using (SQLiteCommand insertCommand = new SQLiteCommand(query, connection))
{
using (SQLiteDataReader dr = insertCommand.ExecuteReader())
{
var newentry = new List<Values>();
while (dr.Read())
{
newentry.Add(new Values()
{
Date = dr["EDate"].ToString(),
Tag = dr["Tag"].ToString(),
Value = dr["Valuex"].ToString(),
Note = dr["Note"].ToString(),
});
}
dr.Close();
Closeconnection();
return newentry;
}
}
getting following error on the above code
Exception thrown: 'System.IndexOutOfRangeException' in System.Data.SQLite.dll
Error System.IndexOutOfRangeException: Index was outside the bounds of the array.
you're reading 'EDate' with dr["EDate"] and it does not exist in the Query you need to add it to your select statement!
string query = "SELECT date(EDate,'utc') as EDate, Tag, Valuex, Note from collections where Account_Number = '1010011' AND Edate >= '2021-01-01'";
Related
I have a very silly problem. I am doing a select, and I want that when the value comes null, return an empty string. When there is value in sql query, the query occurs all ok, but if there is nothing in the query, I have to give a sqlCommand.CommandTimeout greater than 300, and yet sometimes gives timeout. Have a solution for this?
public string TesteMetodo(string codPess)
{
var vp = new Classe.validaPessoa();
string _connection = vp.conString();
string query = String.Format("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = {0}", codPess);
try
{
using (var conn = new SqlConnection(_connection))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn))
{
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
return "";
return codPess;
}
}
}
You should probably validate in the UI and pass an integer.
You can combine the usings to a single block. A bit easier to read with fewer indents.
Always use parameters to make the query easier to write and avoid Sql Injection. I had to guess at the SqlDbType so, check your database for the actual type.
Don't open the connection until directly before the .Execute. Since you are only retrieving a single value you can use .ExecuteScalar. .ExecuteScalar returns an Object so must be converted to int.
public string TesteMetodo(string codPess)
{
int codPessNum = 0;
if (!Int32.TryParse(codPess, out codPessNum))
return "codPess is not a number";
var vp = new Classe.validaPessoa();
try
{
using (var conn = new SqlConnection(vp.conString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = #cod_pess", conn))
{
cmd.Parameters.Add("#cod_pess", SqlDbType.Int).Value = codPessNum;
conn.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
return "";
return codPess;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
how are you ?
i have a problem loading data from DB (connexion string is good, since I can insert data into DB) into my data Table.
my query also works fine, when execute in Sql management studio I received 15 records... so after some lonely search and tries, I come to you.
Here is the code of my function supposed to get Value from DB.
The code stops at 'dt.Load(sqlCommand.ExecuteReader());' , where it seems to search, but i obtain after some seconds , a timeout exeption. And I as I
public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
{
string conn = ConnectionStringHelper.GetIdentityConnectionString();
List<string> conf = new List<string>();
using (SqlConnection dbConnection = new SqlConnection(conn))
{
dbConnection.Open();
SqlCommand sqlCommand = new SqlCommand(#"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE ck.KeyName = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.Add(new SqlParameter("#ConfigurationKey", "PORTAL_THEME"));
if (idBusinessUnit == null)
sqlCommand.Parameters.Add(new SqlParameter("#idBusinessUnit", null)); //DBNull.Value
else
sqlCommand.Parameters.Add(new SqlParameter("#idBusinessUnit", null));
if (idDomain == null)
sqlCommand.Parameters.Add(new SqlParameter("#idDomain", null));// DBNull.Value
else
sqlCommand.Parameters.Add(new SqlParameter("#idDomain", 281));
DataTable dt = new DataTable();
dt.Load(sqlCommand.ExecuteReader());
//dbConnection.Close();
if (dt != null)
if (dt.Rows.Count > 0)
foreach (DataRow dr in dt.Rows)
conf.Add(Convert.ToString(dr["Value"]));
}
return conf;
}
Try this:
SqlCommand sqlCommand = new SqlCommand(#"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE ck.KeyName = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);
sqlCommand .CommandTimeout = 500;
thank you, for your kind attention.I solved it this morning. it was a probleme in the way I excecuted the load of the dataTable. Instead of a dataTable I am using now a DataReader. I precise, that if we use the dataReader, we get the right error message (it s a bonus.) So here is the part of the code I changed (for thoose who want to know) :
public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
{
string conn = ConnectionStringHelper.GetIdentityConnectionString();
string valueRes;
int idConfigurationKey = 0;
if (configurationKey == "PORTAL_THEME") { idConfigurationKey = 3; }
else if (configurationKey == "LOGO_THEME") { idConfigurationKey = 4; }
List<string> conf = new List<string>();
DataTable dt = new DataTable();
using (SqlConnection dbConnection = new SqlConnection(conn))
{
dbConnection.Open();
SqlCommand command = dbConnection.CreateCommand();
SqlTransaction transaction;
transaction = dbConnection.BeginTransaction("SampleTransaction");
command.Connection = dbConnection;
command.Transaction = transaction;
try
{
command.CommandText = #"
SELECT Value
FROM ConfigurationValue cv
INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
WHERE cf.idConfigurationKey = #ConfigurationKey
AND((cf.idDomain = #idDomain) OR(cf.idDomain IS NULL))
AND((cf.idBusinessUnit = #idBusinessUnit) OR(cf.idBusinessUnit IS NULL))";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add(new SqlParameter("#ConfigurationKey", idConfigurationKey));
if (idBusinessUnit == null)
command.Parameters.Add(new SqlParameter("#idBusinessUnit", DBNull.Value)); //DBNull.Value
else
command.Parameters.Add(new SqlParameter("#idBusinessUnit", idBusinessUnit));
if (idDomain == null)
command.Parameters.Add(new SqlParameter("#idDomain", null));// DBNull.Value
else
command.Parameters.Add(new SqlParameter("#idDomain", idDomain));
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string theme = reader["Value"].ToString();
conf.Add(theme);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
}
}
return conf;
}
I am trying to query the MySQL database from a c# application. Below is the code , here I am using parameterized query
public static void ValidateName(MySqlConnection conn,List<Employee> EmpList, string Group)
{
string selectQuery = "Select Name from Employee where Group = #Group AND #Name in (FirstName, LastName);";
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
for (int i = 0; i < EmpList.Count; i++)
{
cmd.Parameters.Add("#Group", MySqlDbType.VarChar).Value = Group;
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
var reader = cmd.ExecuteReader();
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Failed");
}
}
}
But the above code is throwing error in below line saying
cmd.Parameters.Add("#Group", MySqlDbType.VarChar).Value = Group;
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll' #Group has already been defined
This is happening because you are adding the same set of parameters in each iterations. You can either clear then in each iteration or else add them before starting the loop and change the value of existing parameter during each iteration. I think second option would be great. One more thing I have to specify here is about the reader, you have to use reader as an using variable so that each time it will get disposed at the end of the using block and your code works fine. Which means you can try something like this:
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new MySqlParameter("#Group", MySqlDbType.VarChar));
cmd.Parameters.Add(new MySqlParameter("#Name", MySqlDbType.VarChar));
for (int i = 0; i < EmpList.Count; i++)
{
cmd.Parameters["Group"].Value = group;
cmd.Parameters["Name"].Value = EmpList[i].Name;
// rest of code here
using (MySqlDataReader reader = cmd.ExecuteReader())
{
// Process reader operations
}
}
}
I am trying to return data using IEnumerable with given fields, where I am calling the the method I want to reference the data with given field name and return that.
Example, here is the function
public IEnumerable<IDataRecord> GetSomeData(string fields, string table, string where = null, int count = 0)
{
string sql = "SELECT #Fields FROM #Table WHERE #Where";
using (SqlConnection cn = new SqlConnection(db.getDBstring(Globals.booDebug)))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#Fields", SqlDbType.NVarChar, 255).Value = where;
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
Calling:
IEnumerable<IDataRecord> data = bw.GetSomeData("StaffCode, Perms", "BW_Staff", "StaffCode = 'KAA'");
What must I do to return the data this way or what way ?
string staffCode = data["StaffCode"].ToString();
string perms = data["Perms"].ToString();
Thanks for any help
your data variable is a collection of rows. You need to iterate over the collection to do something interesting with each row.
foreach (var row in data)
{
string staffCode = row["StaffCode"].ToString();
string perms = row["Perms"].ToString();
}
Update:
Based on your comment that you only expect GetSomeData(...) to return a single row, I'd suggest 1 of two things.
Change the signature of GetSomeData to return an IDataRecord. and remove "yield" from the implementation.
public IDataRecord GetSomeData(string fields, string table, string where = null, int count = 0)
{
string sql = "SELECT #Fields FROM #Table WHERE #Where";
using (SqlConnection cn = new SqlConnection(db.getDBstring(Globals.booDebug)))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#Fields", SqlDbType.NVarChar, 255).Value = where;
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
return (IDataRecord)rdr;
}
}
}
}
}
Or
var row = data.FirstOrDefault();
if (row != null)
{
string staffCode = row["StaffCode"].ToString();
string perms = row["Perms"].ToString();
}
Remarks:
Your implementation of GetSomeData is incomplete. You are not even using several of the parameters, most importantly the fields parameter. And conceptually in SQL you can't parameterize which fields get returned or which table gets used (etc.), but rather you need to construct a dynamic query and execute it.
Update 2
Here is an implementation of GetSomeData that constructs a proper query (in C# 6, let me know if you need it in an earlier version).
public IEnumerable<IDataRecord> GetSomeData(IEnumerable<string> fields, string table, string where = null, int count = 0)
{
var predicate = string.IsNullOrWhiteSpace(where) ? "" : " WHERE " + where;
string sql = $"SELECT { string.Join(",", fields) } FROM {table} {predicate}";
using (SqlConnection cn = new SqlConnection(db.getDBstring(Globals.booDebug)))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
And here is how you would use it.
IEnumerable<IDataRecord> data = bw.GetSomeData(new[] { "StaffCode", "Perms" }, "BW_Staff", "StaffCode = 'KAA'");
You can either enumerate it or call .FirstOrDefault, it's your choice. Each time you call GetSomeData, it will run the query.
Update 3
GetSomeData implemented with earlier versions of C#
public IEnumerable<IDataRecord> GetSomeData(IEnumerable<string> fields, string table, string where = null, int count = 0)
{
var predicate = string.IsNullOrEmpty(where) ? "" : " WHERE " + where;
string sql = string.Format("SELECT {0} FROM {1} {2}", string.Join(",", fields), table, predicate);
using (SqlConnection cn = new SqlConnection(db.getDBstring(Globals.booDebug)))
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
Trying to retrieve a single value from an oracle database table, with the code below
public int _getProductPrice(string product_id)
{
Int16 price = 0;
string query = string.Format(#"select sum(price) price from sales where product_id = '{0}'", product_id);
string connectionString = String.Format("SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));uid={3};pwd={4};", AppConfig.OraDBHOST, AppConfig.OraDBPORT, AppConfig.OraDBNAME, AppConfig.OraDBUSER, AppConfig.OraDBPWD);
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cm = new OracleCommand(query);
try
{
cm.Connection = connection;
connection.Open();
OracleDataReader reader = cm.ExecuteReader();
reader.Read();
price = reader.GetInt16(0);
}
catch(Exception e) {
throw new Exception(e.Message);
}
}
return price;
}
However the exception returns the "specified method is not supported", not sure which method.
What am i getting wrong?