public ArrayList P2a(string sql)
{
ArrayList result = new ArrayList();
MySqlCommand cmd = new MySqlCommand();
MySqlConnection mysqlconnection = new MySqlConnection(xxx);
cmd.Connection = mysqlconnection;
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Dictionary<string, object> dict = new Dictionary<string, object>();
for (int count = 0; (count <= (reader.FieldCount - 1)); count++)
{
dict.Add(reader.GetName(count), reader[count]);
}
result.Add(dict);
}
return result;
} catch {
return result;
} finally {
cmd.Connection.Close();
}
}
C# Visual Studio 2017 MySQL void return echo problem.
I want to make sure that I print out the result properly.
Example:
ArrayList query = P2a("select id,site,comment from sites");
MessageBox.Show(query[0]["site"].toString());
To use it this way.
Can you make the necessary corrections in the function?
I recommend as a start to change your catch block.
You should be throwing the exception, ideally with more information.
I also recommend that you have an optional list of MySqlParameters (defaults to null), while its not obvious here, since there are no parameters, more than likely you have SQL that is suspectible to SQL injection. In most cases, if you have a where block and its not null, you have done something incorrectly.
Your code does not cleanup the disposable objects, so using will take care of that.
Use generics instead as the list item will now be a dictionary.
public List<Dictionary<String, object>> P2a(string sql, MySqlParameter[] parameters)
{
List<Dictionary<String, object>> result = new List<Dictionary<String, object>>();
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlConnection mysqlconnection = new MySqlConnection(xxx))
{
cmd.Connection = mysqlconnection;
cmd.CommandText = sql;
if (parameters != null)
{
foreach (MySqlParameter p in parameters)
{
cmd.Parameters.Add(p);
}
}
try
{
cmd.Connection.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Dictionary<string, object> dict = new Dictionary<string, object>();
for (int count = 0; (count <= (reader.FieldCount - 1)); count++)
{
dict.Add(reader.GetName(count), reader[count]);
}
result.Add(dict);
}
}
return result;
}
catch (ApplicationException ex)
{
throw new ApplicationException("Error Executing " + sql, ex);
}
finally
{
cmd.Connection.Close();
}
}
}
}
I solved the problem myself
I wrote a new function
public DataTable query(string sql) {
DataTable table = new DataTable();
MySqlConnection connection = null;
MySqlDataReader reader = null;
try {
connection = new MySqlConnection(xxx);
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(sql, connection);
dataAdapter.Fill(table);
return table;
} catch {
return table;
} finally {
if (reader != null)
reader.Close();
if (connection != null)
connection.Close();
}}
use off
DataTable list = query("select * from tablename");
MessageBox.Show(list.Rows["rowsname"]["cellname"].ToString());
Related
I have this code running in form_load event:
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("pp_sp_MachineAndOp", sqlConn);
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
sqlDa.Fill(sqlDt);
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
sqlDa.Dispose();
sqlConn.Close();
}
I get error 'Procedure or function 'pp_sp_MachineAndOp' expects parameter '#MachineAndOpID', which was not supplied.' at line:
sqlDa.Fill(sqlDt);
Important to say that if I open DataTable Visualizer of sqlDt at runtime I see expected results!
Here is a code behind Helper.ExecuteDataTable:
public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
What I am missing?
Remove everything except
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
your Helper.ExecuteDataTable is doing everything. you don't need to replicate same this in your code.
I think your helper class is creating connection with database as your data table has data.
So, try to remove stored proc name and connection object from adaptor and then check.
SqlDataAdapter sqlDa = new SqlDataAdapter();//use this only.
you can use below function(modification required as per your need):
public IDataReader ExecuteReader(string spName, object[] parameterValues)
{
command = GetCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
if (parameterValues != null)
{
for (int i = 0; i < parameterValues.Length; i++)
{
command.Parameters.Add(parameterValues[i]);
}
}
reader = command.ExecuteReader();
if (parameterValues != null)
command.Parameters.Clear();
return reader;
}
I have this method, which I have in the base class that helps me to select anything from the children classes and also to reduce code repetition. The problem is when I call it I get an error which is a NullReferenceException (and when I look it up I find that the command in the method is empty).
This is the method in question:
This way I already know how to use but the other one I don't
SqlCommand command = new SqlCommand("select * from Customers where idCustomer=#idCustomer", OpenConnection());
command.Parameters.AddWithValue("#idCustomer", Id);
SqlDataReader reader = command.ExecuteReader();
Customer Onecustomer = null;
if (reader.Read())
{
Onecustomer = ReadCustomer(reader);
}
protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
SqlCommand command = new SqlCommand();
DataTable dataTable;
DataSet dataSet = new DataSet();
try
{
command.Connection = OpenConnection();
command.CommandText = query;
command.Parameters.AddRange(sqlParameters);
command.ExecuteNonQuery();
adapter.SelectCommand = command;
adapter.Fill(dataSet);
dataTable = dataSet.Tables[0];
}
catch (SqlException e)
{
return null;
throw new Exception("Error :" + e.Message);
}
finally
{
CloseConnection();
}
return dataTable;
}
Here how I call it
string author = "Alfred Schmidt";
int id = 1;
// ExecuteEditQuery("UPDATE Books SET Title =#param1 WHERE idBook =#param2", sqlParameters);
//SqlParameter[] sqlParameters = new SqlParameter[1]
//{
// new SqlParameter ("#param1",author),
//};
SqlParameter[] myparm = new SqlParameter[1];
myparm[0] = new SqlParameter("#Author", SqlDbType.NVarChar, 200);
myparm[0].Value = author;
String query = #"SELECT * FROM Books WHERE Author =#Author";
DataTable dt = ExecuteSelectQuery(query, myparm);
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(dt.Rows.ToString());
}
Console.Write("");
1
Is your OpenConnection() method returns a connection object. It may couse the error, the implementation of the method is not given. Also the adpater is not defined in the code, may be it can be the cause of error too, if it is not initialized.
And i want to say few things about your code:
1) You have and unnecessary command.ExecuteNonQuery(); statement in your ExecuteSelectQuery method.
2) DataAdapter can directly fill DataTable, you dont have to use DataSet.
Here's a proper rewrite of your method.
protected DataTable ExecuteSelectQuery(String query, params SqlParameter[] sqlParameters)
{
using (SqlCommand command = new SqlCommand())
try
{
command.CommandText = query;
command.Parameters.AddRange(sqlParameters);
command.Connection = OpenConnection();
DataTable dataTable = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
adapter.Fill(dataTable);
return dataTable;
}
catch (SqlException e)
{
return null;
throw new Exception("Error :" + e.Message);
}
finally
{
CloseConnection();
}
}
Note that the SqlDataAdapter can Open() and Close() the connection by itself, if the SqlConnection is Closed when Fill is called.
Hi i am trying to store the value of a group of textboxes into a sql database, I have created the database and written the sql script. I have created the connection to sql database from my project when the script runs i get the error
An unhandled exception of type 'System.NotImplementedException' occurred in >PLUPROG.exe
Additional information: The method or operation is not implemented.
Casued by.
public static implicit operator SqlCommand(Sqlcommand v)
{
throw new NotImplementedException();
}
The code for my SQL script is
private void btnAddPlu_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection("Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = PluProg; Integrated Security = True"))
{
string query = "INSERT INTO Departments VALUES (#Name, #Type, #SubDept)";
SqlCommand cmd = new Sqlcommand(query, sqlConn);
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = cbDeptName.Text;
cmd.Parameters.Add("#Type", SqlDbType.NVarChar, 50).Value = cbDeptType.Text;
cmd.Parameters.Add("#SubDept", SqlDbType.NVarChar, 50).Value = cbSubDept.Text;
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch ()
I really don't know what you're asking, but I feel bad that you've asked twice and clearly haven't figured out anything. Take a look at this and see if something answers your question. The following is not optimized/generalized - just basic stuff for you to see what's what and improve on in your own way.
public SqlConnection getConn()
{
return new SqlConnection(getConnString());
}
public string getConnString()
{
return #"Data Source=lily.arvixe.com;Initial Catalog=WM_Crawler;Persist Security Info=True;User ID={myUser};Password={MyPass};Connection Timeout=7000";
}
//This is how you flush a DataTable
public void saveDataTable(string tableName, DataTable table)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (var bulkCopy = new SqlBulkCopy(conn))//, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in table.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, "["+col.ColumnName+"]");
}
bulkCopy.BulkCopyTimeout = 8000;
bulkCopy.DestinationTableName = tableName;
bulkCopy.BatchSize = 10000;
bulkCopy.EnableStreaming = true;
//bulkCopy.SqlRowsCopied += BulkCopy_SqlRowsCopied;
//bulkCopy.NotifyAfter = 10000;
bulkCopy.WriteToServer(table);
}
conn.Close();
}
}
//this is how you select one field from one row
public object scalar(string sql)
{
object ret;
using (SqlConnection conn = getConn())
{
conn.Open();
using (SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
ret = com.ExecuteScalar();
}
conn.Close();
}
return ret;
}
//this is how you execute a command using SQL string (admin functions)
public void nonQuery(string sql)
{
using(SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = sql;
com.CommandTimeout = 5900;
com.ExecuteNonQuery();
}
conn.Close();
}
}
// This is how you execute a query using a predefined, parameterized command (user input)
public void nonQuery_With_Command(SqlCommand com)
{
using (SqlConnection conn = getConn())
{
conn.Open();
using (com)
{
com.Connection = conn;
com.ExecuteNonQuery();
}
conn.Close();
}
}
//this is how you execute several commands under one connection (sql or stored procedure)
public void nonQuery_List_Command(List<SqlCommand> comList)
{
using (SqlConnection conn = getConn())
{
conn.Open();
foreach (SqlCommand com in comList)
{
using (com)
{
com.Connection = conn;
try
{
com.ExecuteNonQuery();
}
catch(Exception n1)
{
Console.WriteLine(n1.Message);
Console.WriteLine(com.Parameters[1].Value.ToString());
}
}
}
conn.Close();
}
}
//This returns column names from a specific table (example of a datareader)
private List<string> get_Column_Names(string tableName)
{
List<string> ret = new List<string>();
using (SqlConnection conn = getConn())
{
conn.Open();
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = "select column_Name from INFORMATION_SCHEMA.COLUMNS where table_Name = '" + tableName + "'";
com.CommandTimeout = 600;
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
ret.Add(Convert.ToString(read[0]));
}
}
conn.Close();
}
return ret;
}
//This converts a reader to a class using fields. It is not optimized and is inefficient, but allows you to see what's happening. Yu can optimize it yourself
public static object[] sql_Reader_To_Type(Type t, SqlDataReader r)
{
List<object> ret = new List<object>();
while (r.Read())
{
FieldInfo[] f = t.GetFields();
object o = Activator.CreateInstance(t);
for (int i = 0; i < f.Length; i++)
{
string thisType = f[i].FieldType.ToString();
switch (thisType)
{
case "System.String":
f[i].SetValue(o, Convert.ToString(r[f[i].Name]));
break;
case "System.Int16":
f[i].SetValue(o, Convert.ToInt16(r[f[i].Name]));
break;
case "System.Int32":
f[i].SetValue(o, Convert.ToInt32(r[f[i].Name]));
break;
case "System.Int64":
f[i].SetValue(o, Convert.ToInt64(r[f[i].Name]));
break;
case "System.Double":
double th;
if (r[f[i].Name].GetType() == typeof(DBNull))
{
th = 0;
}
else
{
th = Convert.ToDouble(r[f[i].Name]);
}
}
try { f[i].SetValue(o, th); }
catch (Exception e1)
{
throw new Exception("can't convert " + f[i].Name + " to double - value =" + th);
}
break;
case "System.Boolean":
f[i].SetValue(o, Convert.ToInt32(r[f[i].Name]) == 1 ? true : false);
break;
case "System.DateTime":
f[i].SetValue(o, Convert.ToDateTime(r[f[i].Name]));
break;
default:
throw new Exception("Missed data type in sql select ");
}
}
ret.Add(o);
}
return ret.ToArray();
}
//these are basic (rudimentary) ways of converting class to DataTable
public static DataTable create_DataTable_From_Generic_Class(Type t)
{
DataTable d = new DataTable();
PropertyInfo[] pI = t.GetProperties();
for (int i = 0; i < pI.Length; i++)
{
DataColumn dC = new DataColumn(pI[i].Name, pI[i].PropertyType);
d.Columns.Add(dC);
}
return d;
}
public static object[] Create_Datatable_Row_From_Generic_Class(Type t, object instance, DataTable dt)
{
PropertyInfo[] p = t.GetProperties();
object[] ret = new object[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
var temp = t.GetProperty(dt.Columns[i].ColumnName);
ret[i] = temp.GetValue(instance);
}
return ret;
}
I'm trying to use a SQL query in SqlCommand and I'd like to see the complete result set that is returned from SQL Server database, and return Json format after that.
So here is the code in controller:
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT v.date, v.name, v.numbers FROM view as v GROUP BY v.date,v.mane,v.numbers ORDER BY v.date,v.mane,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
// In this part below, I want the SqlDataReader to
// read all of the records from database returned,
// and I want the result to be returned as Array or
// Json type, but I don't know how to write this part.
while(reader.Read())
{
ArrayList result = new ArrayList();
foreach(int i in reader)
// this line below was the code I wrote before.
// But since my query returns multiple
// types (datetime, string, decimal, etc..),
// I don't know what C# command I can use to return
// the results in foreach loop. Or say I even don't
// need a for/foreach loop.
result.Add(reader.GetValue(i));
return Json(result, JsonRequestBehavior.AllowGet);
}
reader.Close();
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
Anyone can help me to make this work? I will be greatly appreciated.
Kevin
public class data {
public DateTime date {get;set;}
public string name {get;set;}
public int numbers {get;set;}
}
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT DISTINCT v.date, v.name, v.numbers FROM view as v ORDER BY v.date,v.name,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
// In this part below, I want the SqlDataReader to
// read all of the records from database returned,
// and I want the result to be returned as Array or
// Json type, but I don't know how to write this part.
while(reader.Read())
{
List<data> result = new List<data>();
var d=new data();
d.date=reader[0]; // Probably needs fixing
d.name=reader[1]; // Probably needs fixing
d.numbers=reader[2]; // Probably needs fixing
result.Add(data);
}
reader.Close();
return Json(result, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
or
public class data {
public DateTime date {get;set;}
public string name {get;set;}
public int numbers {get;set;}
}
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT DISTINCT v.date, v.name, v.numbers FROM view as v ORDER BY v.date,v.name,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
var dt=new DataTable();
dt.Load(myDataReader);
List<DataRow> result=dt.AsEnumerable().ToList();
reader.Close();
return Json(result, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
or (just the interesting part):
var dt=new DataTable();
dt.Load(myDataReader);
object[] result = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++) {
result[i] = dt.Rows[i].ItemArray;
}
You can use this extension:
public static string ExecuteToJson(this SqlCommand cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
using (DataTable dt = new DataTable())
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return JsonConvert.SerializeObject(rows);
}
}
}
and the usage:
string connectionString = "** connstr **";
string query = "SELECT * FROM `table`";
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, conn))
{
string json = command.ExecuteToJson();
}
}
}
catch (Exception)
{
}
I have a bunch of methods like so in my DAL in VS 2010. When I run the "new" Code Analysis option i get the message - Warning CA2000 object 'comm' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'comm' before all references to it are out of scope.
I understand I could use another using statement for the SQLCommand however if prefer to do it like I have with the Try/Finally block. My understanding is the Finally block executes last and does the cleanup. Does anyone see anything wrong here with my dispose call?
public List<Product> GetAllProducts()
{
List<Product> prodList = new List<Product>();
using (SqlConnection connection = new SqlConnection(GetConnection()))
{
SqlCommand comm = new SqlCommand("GetAllProducts", connection);
connection.Open();
comm.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = comm.ExecuteReader();
try
{
while (dr.Read())
{
Product obj = new Product();
obj.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
obj.Product = dr["Product"].ToString();
//etc....
prodList.Add(obj);
}
}
finally
{
comm.Dispose();
dr.Close();
}
}
return prodList;
}
}
If any of these three statements throw an exception, comm will not be disposed.
connection.Open();
comm.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = comm.ExecuteReader();
Your try block would need to encompas these statements as well.
Put a using block around the command and dataReader so that they will always be disposed.
public List<Product> GetAllProducts()
{
List<Product> prodList = new List<Product>();
using (SqlConnection connection = new SqlConnection(GetConnection()))
{
using (SqlCommand comm = new SqlCommand("GetAllProducts", connection))
{
connection.Open();
comm.CommandType = CommandType.StoredProcedure;
using (SqlDataReader dr = comm.ExecuteReader())
{
try
{
while (dr.Read())
{
Product obj = new Product();
obj.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
obj.Product = dr["Product"].ToString();
//etc....
prodList.Add(obj);
}
}
}
}
}
return prodList;
}
List<Measure_Type> MeasureList = new List<Measure_Type>();
SqlConnection conn = null;
SqlDataReader rdr = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["Conn"];
conn.Open();
cmd = new SqlCommand("SELECT Measure_ID, Mea_Name FROM MeasureTable WHERE IsActive=1", conn);
rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
{
while (rdr.Read())
{
MeasureTypeList.Add(new Measure_Type { MeasureTypeID = Convert.ToInt32(rdr[0]), MeasureTypeName = rdr[1].ToString() });
}
}
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, "Log");
}
finally
{
cmd.Dispose();
// close the reader
if (rdr != null) { rdr.Close(); }
// Close the connection
if (conn != null) { conn.Dispose(); }
}
return MeasureTypeList;
create conn = new SqlConnection(); inside the try block and then open it to solve this bug.