Read a sql query with C# [duplicate] - c#

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 7 years ago.
I tried to get my sql query read, but it does not really work. It is all working until it comes to the query part and then on the line:
rst = query.ExecuteReader();
It gets an error:
Connection property has not been initialized.
Does anyone know how to handle this?
Chart chart = new Chart();
StringBuilder xmlStr = new StringBuilder();
StringBuilder strCategories = new StringBuilder();
StringBuilder strProcesses = new StringBuilder();
StringBuilder strTasks = new StringBuilder();
xmlStr.Append("<chart logoURL='../../Images/Piktogramme/" + chart.Image + "' caption='" + chart.Caption + "' theme='flat'" + " dateformat='dd/mm/yyyy' showTaskLabels='1'>"); // attributes will go here
// Category for each month
for (int i = -12; i < 6; i++)
{
DateTime today = DateTime.Now;
today = today.AddMonths(i);
strCategories.Append("<category start='1/" + today.Month + "/" + today.Year + "' end='" + DateTime.DaysInMonth(today.Year, today.Month) + "/" + today.Month + "/" + today.Year + "' name='" + today.ToString("MMM") + "' />");
}
// Get the connection string
string connStr = ConfigurationManager.ConnectionStrings["CRM_SQL"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
// Establish the connection with the database
conn.Open();
// Construct and execute SQL query which would return the total amount of sales for each year
SqlCommand query = new SqlCommand();
// Begin iterating through the result set
SqlDataReader rst;
query.CommandText = "SELECT * from table";
rst = query.ExecuteReader();
while (rst.Read())
{
// Construct the chart data in XML format
strProcesses.AppendFormat("<process name='{1}' id='{0}' />", rst[0], rst[1]);
strTasks.AppendFormat("<task name='{0}' processid='{1}' start='{2}' end='{3}' />", rst[4], rst[0], rst[2], rst[3]);
}
DateTime today = DateTime.Now;
xmlStr.Append("<trendlines><line start='" + DateTime.DaysInMonth(today.Year, today.Month) + "/" + today.Month + "/" + today.Year + "' displayvalue='Heute'/></trendlines>");
// End the XML string
xmlStr.Append("<categories>" + strCategories.ToString() + "</categories> <processes>" + strProcesses.ToString() + "</processes> <tasks width='10'>" + strTasks.ToString() + "</tasks> </chart>");
// Close the result set Reader object and the Connection object
rst.Close();
conn.Close();
}
return xmlStr.ToString();
}

Your SqlCommand object has no link to your SqlConnection.
Replace the line:
SqlCommand query = new SqlCommand();
By:
SqlCommand query = conn.CreateCommand();
PS: Like SqlConnection, SqlCommand and SqlDataReader are also disposable, so you can/should also use using.
And the line conn.Close(); is useless because using will take care of it.

One way to do this;
var query = new SqlCommand("SELECT * from table", conn);
another way is assigning the connection string
query.connection = conn;

Add following
query.Connection=conn;
after
SqlCommand query = new SqlCommand();

try this :
using (SqlConnection conn = new SqlConnection(connStr))
{
// Establish the connection with the database
conn.Open();
using (SqlCommand query = new SqlCommand("SELECT * from table", conn))
{
query.CommandType = CommandType.Text;
using (var rst = query.ExecuteReader())
{
while (rst.Read())
{
strProcesses.AppendFormat("<process name='{1}' id='{0}' />", rst[0], rst[1]);
strTasks.AppendFormat("<task name='{0}' processid='{1}' start='{2}' end='{3}' />", rst[4], rst[0], rst[2], rst[3]);
}
}
}
DateTime today = DateTime.Now;
xmlStr.Append("<trendlines><line start='" + DateTime.DaysInMonth(today.Year, today.Month) + "/" + today.Month + "/" + today.Year + "' displayvalue='Heute'/></trendlines>");
// End the XML string
xmlStr.Append("<categories>" + strCategories.ToString() + "</categories> <processes>" + strProcesses.ToString() + "</processes> <tasks width='10'>" + strTasks.ToString() + "</tasks> </chart>");
conn.Close();
}

Related

Month not increasing after Increment of a Year in SQL Server using C#

I am saving due date of every transaction with next number of month. It is working perfect for 2019, but doesn't work for 2020 and so on.
string Due_Date_Sample;
DateTime Due_Date_var;
public static string format = "yyyy-MM-dd";
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') AS Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
Due_Date_var = Convert.ToDateTime(Due_Date_var.ToString(format)).AddMonths(1);
commandstring1 = "INSERT INTO Transactions (Trans_Code,Plot_Code,Plot_No,Inst_No,Inst_Amt,Status,Due_Date,Balance) values ('"
+ Transaction_Code_var + "','" + Plot_Code_var + "','" + Plot_No_var + "','"
+ Inst_No_var + "','" + Inst_Amt_var + "','Due','" + Due_Date_var.ToString(format) + "','" + (Bal_var - int.Parse(Inst_Amt_var)) + "');";//Saving Transactions
SqlCommand sqlCmd = new SqlCommand(commandstring1, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
I have tested your problem using Entity framework it is working correct no need such long code as you written and EF is recommended by Microsoft for new Desktop and web apps check simple code in using EF
using (var context = new ProductionContext())
{
DateTime PayDate = PaymentDatePicker.Value; //Payment or Transaction Date
DateTime DueDate = PayDate.AddMonths(1); // due date = Payment date + one month
var install = new Instalment(); // object of instalment class/table
install.PaymentDate = PayDate;
install.NextDueDate = DueDate;
context.Instalments.Add(install);
context.SaveChanges();
}

Slow performance importing MS Access database into SQL Server

I have a problem with importing items from an MS Access .mdb database file into SQL Server. I wrote a C# application in practice database that extrapolates the data in a .mdb database and places them in a table in a SQL Server database.
My problem is that the .mdb database contains about 300,000 articles which are to be inserted with all of the controls inside the SQL Server database. The .mdb file is selected by the user.
How can I speed up the import of the articles?
This is my C# code:
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
// SqlConnection conn2 = db.apriconnessione();
try
{
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
string querycontalinee = "SELECT count(*) from ARTICOLI";
OleDbCommand command = new OleDbCommand(query, dbConn);
OleDbCommand commandcontalinee = new OleDbCommand(querycontalinee, dbConn);
dbConn.Open();
int linee = (int)commandcontalinee.ExecuteScalar();
OleDbDataReader reader = command.ExecuteReader();
Articolo a;
labelstatoaggiornamento.Show();
progressBarstatoaggiornamento.Show();
progressBarstatoaggiornamento.Style = ProgressBarStyle.Continuous;
progressBarstatoaggiornamento.Minimum = 0;
progressBarstatoaggiornamento.Maximum = linee;
progressBarstatoaggiornamento.Step = 1;
SqlConnection conn = db.apriconnessione();
while (reader.Read())
{
String CodMarca = "" + reader.GetValue(0).ToString();
String CodArt = "" + reader.GetValue(1).ToString().Replace("'", ""); ;
String Fornitore = "COMET";
String Descrizione = "" + reader.GetValue(2).ToString();
String UM = "" + reader.GetValue(3).ToString();
String PrezzoNetto = "" + reader.GetValue(4).ToString();
String PrezzoCasa = "" + reader.GetValue(5).ToString();
DateTime DataAggiornamento = DateTime.Now;
decimal Prezzo = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
decimal PrezzoListino = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
a = new Articolo(CodArt, CodMarca);
a.db = db;
if (a.ControlloDisponibilitàCOMET() == true)
{
string queryAggiornamento = "Update Articolo Set Descrizione='" + Descrizione + "', UM='" + UM + "', Prezzo='" + Prezzo + "',PrezzoListino='" + PrezzoListino + "',DataAggiornamento='" + DataAggiornamento + "',Stato='Aggiornamentoincorso' Where CodMarca = '" + CodMarca + "' AND CodArt = '" + CodArt + "' AND Importato = 'COMET' and Fornitore='COMET' ";
SqlCommand commaggiorna = new SqlCommand(queryAggiornamento, conn);
try
{
commaggiorna.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(" " + ex);
}
}
else
{
string query2 = "INSERT INTO Articolo (CodMarca, CodArt, Fornitore, Importato, Descrizione, UM, Prezzo, PrezzoListino, Stato) VALUES (#CodMarca, #CodArt, #Fornitore, #Importato, #Descrizione, #UM, #Prezzo, #PrezzoListino, #Stato)";
SqlCommand myCommand = new SqlCommand(query2, conn);
myCommand.Parameters.AddWithValue("#CodMarca", CodMarca);
myCommand.Parameters.AddWithValue("#CodArt", CodArt);
myCommand.Parameters.AddWithValue("#Fornitore", Fornitore);
myCommand.Parameters.AddWithValue("#Importato", Fornitore);
myCommand.Parameters.AddWithValue("#Descrizione", Descrizione);
myCommand.Parameters.AddWithValue("#UM", UM);
decimal PrezzoNetto2 = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#Prezzo", PrezzoNetto2);
decimal PrezzoCasa2 = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#PrezzoListino", PrezzoCasa2);
DateTime dt = Convert.ToDateTime(DataAggiornamento);
myCommand.Parameters.AddWithValue("#Stato", "Aggiornamentoincorso");
myCommand.ExecuteNonQuery();
}
progressBarstatoaggiornamento.PerformStep();
int percent = (int)(((double)progressBarstatoaggiornamento.Value / (double)progressBarstatoaggiornamento.Maximum) * 100);
progressBarstatoaggiornamento.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBarstatoaggiornamento.Width / 2 - 10, progressBarstatoaggiornamento.Height / 2 - 7));
}
string queryNonDisponibili = "Update Articolo Set Stato='Nondisponibile' where Stato!='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
string queryNonDisponibili2 = "Update Articolo Set Stato='Disponibile' where Stato='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
SqlCommand comm = new SqlCommand(queryNonDisponibili, conn);
SqlCommand comm2 = new SqlCommand(queryNonDisponibili2, conn);
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
Console.WriteLine("\n Passaggio Completato");
conn.Close();
db.chiudiconnessione();
dbConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("La password è errata oppure " + ex);
}
Consider using SqlBulkCopy. Since you are running sql queries I would suggest you'd work server side as much as possible. Create a temp table in Sql Server, add all records to a datatable or array of datarows and use SqlBulkCopy to import. I think that is the fastest way to move all records to Sql Server.
From there you can synchronize the two tables in Sql Server with only a few queries.
I would use SqlBulkCopy ...
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
SqlConnection conn2 = db.apriconnessione();
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
OleDbDataAdapter da = new OleDbDataAdapter(query,dbConn);
DataTable dt = new DataTable();
da.Fill(dt);
conn2.Open();
SqlBulkCopy bulk = new SqlBulkCopy(conn2);
bulk.DestinationTableName = "ARTICOLI";
bulk.WriteToServer(dt);
conn2.close();

C# MySQL Query is not working

Error message is,
Connection must be valid and open.
Is this code wrong? How can i solve the problem?
string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
MySqlCommand insertCommand = new MySqlCommand();
conn.Open();
for (int i = 0; i < 10; i++)
{
insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
" SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
" WHERE NOT EXISTS (" +
" SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";
insertCommand.ExecuteNonQuery();
}
conn.Close();
}
Before your for loop need to set connection for your CommandObject like:
InsertCommand.Connection = conn;
You need to assign the connection to your command by using the connection object you created conn.
MySqlCommand insertCommand = conn.CreateCommand();
So, your code goes like this:
string strConn = "server = localhost; user = root; database = ****; port = 3306; password = ****; Charset = utf8";
using (MySqlConnection conn = new MySqlConnection(strConn))
{
MySqlCommand insertCommand = conn.CreateCommand();
conn.Open();
for (int i = 0; i < 10; i++)
{
insertCommand.CommandText = "INSERT INTO master (col_name, col_code)" +
" SELECT * from (select '" + _name[i] + "', '" + _code[i] + "') as tmp" +
" WHERE NOT EXISTS (" +
" SELECT col_code FROM master WHERE col_code = '" + _name[i] + "') limit 1;";
insertCommand.ExecuteNonQuery();
}
conn.Close(); //you don't need this.
}
No need to close the connection by conn.Close(); because the connection gets automatically closed when the using block is exited.
using (MySqlConnection conn = new MySqlConnection(strConn))
{
//your code
}

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

Problem in using DataSet

I have first manually created a DataSet in my project name recvd.xsd having corresponding recvd.xss. On my button click event i have done the following coding.
try
{
DataSet recvd_REPORT = new DataSet();
DataTable REPORT = new DataTable();
String dd_webCofig = ConfigurationManager.ConnectionStrings["server2"].ConnectionString;
OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig);
ddlistconn.Open();
REPORT = recvd_REPORT.Tables["REPORT"];
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = typeof(System.Int32);
myDataColumn.ColumnName = "RECEIVED";
myDataColumn.ReadOnly = false;
myDataColumn.Unique = false;
// Add the Column to the DataColumnCollection.
REPORT.Columns.Add(myDataColumn);
string query = "SELECT case_no as \"RECEIVED\" from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
Response.Write(query);
OdbcCommand cmd = new OdbcCommand(query, ddlistconn);
OdbcDataReader loginMyReader = cmd.ExecuteReader();
OdbcDataAdapter adptr = new OdbcDataAdapter(query, ddlistconn);
adptr.Fill(REPORT);
ddlistconn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
I am getting the error as
Object reference not set to an instance of an object.
If i remove as \"RECEIVED\" from my SQL query and simply execute my SQL query than the result of my query is as follows (varies depending on user input)
200200000452011 ......, n numbers of 12 digit number.
Please help me to remove the error as to why am i not able to bind to DataTable.
I am getting the error before Response.Write(query); is executed, why is that problem?
I removed the try catch block and now i get the error as
try
SELECT case_no as `RECEIVED` ...
or just
SELECT case_no as RECEIVED ...
Anyway the correct DataSet filling code should look like this:
DataSet ds = new DataSet();
using (OdbcConnection connection = new OdbcConnection(connectionString))
using (OdbcCommand command = new OdbcCommand(sqlQuery, connection)
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command)
{
adapter.Fill(ds);
}
In your SQL instead of \"RECIEVED\" have you tried just RECIEVED, no quotes?
You need not to use \"RECEIVED\" in the query, you can use like below.
query = "SELECT case_no as [RECIEVED] from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
you can write query as like
query = "SELECT case_no as RECIEVED from dcpanaji.Civil_t where dt_regis > '" + txtStartDate.Text + "' AND dt_regis < '" + txtEndDate.Text + "' AND court_no = " + DropDownList1.SelectedItem + "";
check like that....

Categories

Resources