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....
Related
I am working on a code in C# where I used OLEDB connection string to connect MS access database.
I have a form where I show data from database in datagridview on some criteria.
Below are criteria:
a) Person (come from database in
b) Process (come from database in textbox)
c) From Date (Datetimepicker)
d) To Date (Datetimepicker)
Result what I want: first I select person and than process and than From Date and then To date and click on View Button. which should show data from MS-Access based on above criteria I selected.
I've tried below methods:
Code:
1. For Person and Process filter:
DataView DV = new DataView(dt1);
DV.RowFilter = string.Format("[Person] LIKE '%{0}%'", textBox5.Text);
dataGridView1.DataSource = DV;
For Date Time between Two date I tried many and Google lots but not find answer. I tried below:
a)
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
string queryString = "";
queryString = "SELECT * FROM Table1 WHERE dob BETWEEN #startdate AND #enddate";
System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(queryString, con);
sqlCmd.Parameters.Add("#startdate", System.Data.SqlDbType.Date).Value = textBox7.Text;
sqlCmd.Parameters.Add("#enddate", System.Data.SqlDbType.Date).Value = textBox8.Text;
System.Data.SqlClient.SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd);
System.Data.DataSet dataSet = new System.Data.DataSet();
dataAdapter.Fill(dataSet);
GridView1.DataSource = dataSet;
GridView1.DataBind();
b)
string FD = "";
FD = dateTimePicker4.Value.ToString("dd-MM-yyyy");
string TD = "";
TD = dateTimePicker5.Value.ToString("dd-MM-yyyy");
connection.Close();
connection.Open();
OleDbCommand command123 = new OleDbCommand();
command123.Connection = connection;
string query123 = "select * from Table1 where [P Date] between date '"# + dateTimePicker4.Text.ToString() + #"' and date '"# + dateTimePicker5.Text.ToString() + #"'"
command123.CommandText = query123;
OleDbDataAdapter da123 = new OleDbDataAdapter(command123);
DataTable dt123 = new DataTable();
da123.Fill(dt123);
dataGridView1.DataSource = dt123;
c)
DataTable dt = new DataTable();
da.Fill(dt);
DataView DV = new DataView(dt1);
DV.RowFilter = string.Format("[P Date] >=" + textBox7.Text + " and <" + textBox8.Text + "");
dataGridView1.DataSource = DV;
d)
DataTable dt1 = new DataTable();
DataView DV = new DataView(dt1);
//DV.RowFilter = "[P Date] IN (#11/01/2019#, #11/11/2019#)";
//DV.RowFilter = "[P Date] >=#"+dateTimePicker4.Text+"# and [P Date] <=#"+dateTimePicker5.Text+"#";
//dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values
//DV.RowFilter ="([P Date] >=CDate('dateTimePicker4.Text')) and ([P Date] <=CDate('dateTimePicker5.Text'))";
//DV.RowFilter = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "([P Date]>=#{dateTimePicker4.text}#) and ([P Date] <=#{dateTimePicker5.Text}#)");
dataGridView1.DataSource = DV;
For connection I am trying OLEDB connection.
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DatabasePath.accdb;
Jet OLEDB:Database Password=password";
connection.Close();
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
//Select all column use belw query
string query = "select * from Table1";
command1.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command1);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
this code is working but problem is that it shows all data not based on criteria based data.
I expect the output in Datagridview based on all criteria. Show only data which falls under all criteria.
I don't see you describing what's wrong with your results. If you are asking for a general help how to do it, here is one example. Bear in mind: The example is simple and does not use parametric query. That's up to you.
Converted C#
string wQueryCreated, wQueryChanged, wQueryCreatedBy, wQueryChandedBy;
if (this.fiCreated.Checked == true)
wQueryCreated = " AND DateCreated >= '" + Format(this.dtpFiCreatedOd.Value, "yyyy-MM-dd 00:00") + "' AND DateCreated <= '" + Format(this.dtpFiCreatedDo.Value, "yyyy-MM-dd 23:59") + " ' ";
else
wQueryCreated = "";
if (this.fiChanged.Checked == true)
wQueryChanged = " AND DateModified BETWEEN '" + Format(this.dtpDateChangedFrom.Value, "yyyy-MM-dd") + "' AND '" + Format(this.dtpDateChangedTo.Value, "yyyy-MM-dd") + "' ";
else
wQueryChanged = "";
if (this.fiCreatedBy.Checked == true)
wQueryCreatedBy = " AND PersonCreatedBy = " + this.fiCreatedBy.SelectedValue + " ";
else
wQueryCreatedBy = "";
if (this.fiChandedBy.Checked == true)
wQueryChandedBy = " AND PersonModifiedBy = " + this.fiChandedBy.SelectedValue + " ";
else
wQueryChandedBy = "";
// use query conditions in SELECT statement
queryString = "SELECT * FROM Table1 WHERE DateDeleted IS NULL " + wQueryCreated + wQueryChanged + wQueryCreatedBy + wQueryChandedBy + "; ";
Original VB.NET:
Dim wQueryCreated, wQueryChanged, wQueryCreatedBy, wQueryChandedBy As String
If Me.fiCreated.Checked = True Then ' filter date created
wQueryCreated = " AND DateCreated >= '" & Format(Me.dtpFiCreatedOd.Value, "yyyy-MM-dd 00:00") & "' AND DateCreated <= '" & Format(Me.dtpFiCreatedDo.Value, "yyyy-MM-dd 23:59") & " ' "
else
wQueryCreated = ""
End If
If Me.fiChanged.Checked = True Then ' filter datechanged
wQueryChanged = " AND DateModified BETWEEN '" & Format(Me.dtpDateChangedFrom.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.dtpDateChangedTo.Value, "yyyy-MM-dd") & "' "
else
wQueryChanged = ""
End If
If Me.fiCreatedBy.Checked = True Then ' filter chandged by person
wQueryCreatedBy = " AND PersonCreatedBy = " & Me.fiCreatedBy.SelectedValue & " "
else
wQueryCreatedBy = ""
End If
If Me.fiChandedBy.Checked = True Then ' filter modified by person
wQueryChandedBy = " AND PersonModifiedBy = " & Me.fiChandedBy.SelectedValue & " "
else
wQueryChandedBy = ""
End If
' use query conditions in SELECT statement
queryString = "SELECT * FROM Table1 WHERE DateDeleted IS NULL " & wQueryCreated & wQueryChanged & wQueryCreatedBy & wQueryChandedBy & "; "
This examples uses 4 conditions, taking information from 6 fields in total (dtp prefixes mean DateTimePicker). Notice a bit different date handling between first and second condition, which do similar thing.
Also notice, that this method requires 1 fixed condition. It could be 1=1, but obvously you usually use it like I did in the example, so i.e. to exclude soft-deleted rows (DateDeleted IS NULL). You need 1 fixed condition so that you don't have to care about the beginning " AND " in the rest of the conditions, regardless of their usage.
You can use "endless" conditions and combine them, even of a different data types. If you need to restrict to combination of conditions, validate they are filled in before you run the query. Obviously, you don't have to test for checked CheckBoxes, you can check for ComboBox1.SelectedValue > -1 (something is selected in ComboBox), or TextBox1.Text.Length >= 3 (at least 3 characters are entered into a TextBox), etc.
During find data between two days, getting error "there is no row at position 0"
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Demo"].ConnectionString.ToString());
string str = "select * from sample where name='" + Session["name"] + "' and date between '" + txtfirstdate.Text + "' and '" + txtenddate.Text + "'";
MySqlCommand cmd = new MySqlCommand(str, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet set = new DataSet();
connection.Open();
adapter.Fill(set);
connection.Close();
//var table = set.Tables[0];
if (set != null)
{
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}
Read the Error Message. Your result set table has no rows.
Replace u r if Condition.
if (set.Tables[0].Rows.Count > 0) {
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}
I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.
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 am very new to sqlite and c# and trying exporting a csv file to sqlite database using dataset.
but I get this error.
SQL logic error or missing database
no such column: P17JAW
code:
string strFileName = "I:/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
CSV FILE CONTAINS
Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4
Your problem is with the single quotes missing for VRM your query should be like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
( '" + Id + "','" + VRM + "'," + Points + ")";
//^^ ^^
From the values it appears that ID is of integer type, you can remove single quotes around ID.
You should parameterized your query that will save your from these errors. I am not sure if parameters are supported by SQLiteCommand if they are you can do something like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
(#Id,#VRM,#Points)";
and then
command.Parameters.AddWithValue("#id", Id);
command.Parameters.AddWithValue("#VRM", VRM);
command.Parameters.AddWithValue("#Points", Points);