I have a couple of days to come up with a solution to my problem and I can not. When running the following code:
OleDbConnection MyconnectionBDD = null;
MyconnectionBDD = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + bdd.Text);
//MyconnectionBDD = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + bdd.Text);
MyconnectionBDD.Open();
OleDbCommand cmdBDD = MyconnectionBDD.CreateCommand();
OleDbDataReader dbReaderBDD = null;
string queryBDD;
queryBDD = "SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '" + int.Parse(dbReaderExcel.GetValue(0).ToString().Substring(3, 2)) + "*'";
//queryBDD = "SELECT MAX(Clientes.Codigo) FROM Clientes WHERE Codigo LIKE '17*'";
cmdBDD.CommandText = queryBDD;
cmdBDD.CommandType = CommandType.Text;
dbReaderBDD = cmdBDD.ExecuteReader();
if (dbReaderBDD.HasRows)
{
dbReaderBDD.Read();
//string codEmp = dbReaderBDD.GetString(0); //GetValue(0).ToString();
MessageBox.Show(dbReaderBDD["CodEmp"].ToString());
MessageBox.Show(dbReaderBDD.GetValue(0).ToString()); //GetInt64(0).ToString());
//if (dbReaderBDD.GetValue(0).ToString() != "")
if (!String.IsNullOrEmpty(dbReaderBDD.GetValue(0).ToString()))
if (dbReaderBDD.GetValue(0).ToString().Length == 6)
last_codigoCli = int.Parse(dbReaderBDD.GetValue(0).ToString().Substring(1, 5));
else
last_codigoCli = int.Parse(dbReaderBDD.GetValue(0).ToString().Substring(2, 5));
last_codigoCli_Revisado = last_codigoCli;
}
dbReaderBDD.Close();
It returned an empty value, but if I run the query in Access it return a correct value:
SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '17*'
Please can someone help me? Thanks
Sorry, the query would be:
queryBDD = "SELECT MAX(Clientes.Codigo) AS CodEmp FROM Clientes WHERE Clientes.Codigo LIKE '" + int.Parse(dbReaderExcel.GetValue(0).ToString().Substring(3, 2)) + "%'";
As the * is the wildcard in Access, I thought that the query had to put a * but was %
Thanks
Related
can anyone help me? i am getting null output. though data exists in database.
string retrivenp = "select emp_email from E_details where emp_ID ='" + c_c +
"'AND emp_name = '" + s_s + "'AND emp_address = '" + n_n +
"'AND Date_joining = '" + Calendar1.SelectedDate + "'";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.ToString();
Label1.Text = url_path.ToString();
}
}
}
i think the string with many quotes is the problem when it will be executed it may give the wrong query
use command parameters it's better
string retrivenp = "select emp_email from E_details where emp_ID = ? AND emp_name = ? AND emp_address = ? AND Date_joining = ?";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
comm1.Parameters.Add("#p1", OleDbType.Int).Value = c_c;
comm1.Parameters.Add("#p2", OleDbType.Text).Value = s_s;
comm1.Parameters.Add("#p3", OleDbType.Text).Value = n_n;
comm1.Parameters.Add("#p4", OleDbType.Date).Value = Calendar1.SelectedDate;
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.GetString(0);
Label1.Text = url_path.ToString();
}
read.Close();
}
}
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();
}
I want to select a sentence from the database, but i don't know how to write the code. I will search for a number by reading lines from the textbox.
for (int i = 0; i < lines.GetUpperBound(0); i++)
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query1 = "SELECT TOP 1 * FROM SolozinnenTabel WHERE Faciliteitnummer = " + lines[i] + " AND Paragraaf LIKE '" + AlineaKinderenNaam + "%' ORDER BY rnd(ID)";
command.CommandText = query1;
OleDbDataReader reader1 = command.ExecuteReader();
while (reader1.Read()) {
RichAccoText.Text = RichAccoText.Text + reader1["Zin"].ToString();
RichFacilityText.Lines = RichFacilityText.Lines.Where(line => line != lines[i]).ToArray();
}
}
This code works but I only can search for one line and search them in the textbox. So I want something like this:
string query1 = "SELECT TOP 1 * FROM CombizinnenTabel WHERE (Faciliteitnummer1= " + lines[a] + " AND Faciliteitnummer2= " + lines[a] + ") AND Paragraaf LIKE '" + AlineaAccommodatieNaam + "%' ORDER BY rnd(ID)";
lines[a] = 80, but I want to search:
If Faciliteitnummer1 = lines[80] en Faciliteitnummer2 = lines[48]and Faciliteitnummer3 = lines[18], then select this sentence.....
If (Faciliteitnummer1 = lines[80] en Faciliteitnummer2 = lines[10]and Faciliteitnummer3 = lines[0], then select this sentence....
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.
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....