dataset datetime format problem - c#

I am having a problem with datetime format in a dataset.
In the database date format is:10/5/2009 10:10:10
but i get an error:FormatException, when attempting to fill the DataSet:
string query = "SELECT * FROM teklif";
c.db = new SQLiteDataAdapter(query, c.con);
c.db.Fill(ds); // Error Here...
dt = ds.Tables[0];
How do I resolve this issue?

It would appear that you are not initializing the adapter right.
MySQLiteConn = new SQLiteConnection("Data Source=" + fileName +
"; Compress = TRUE;");
SQLiteCommand cmd = MySQLiteConn.CreateCommand();
SQLiteDataAdapter dr = new SQLiteDataAdapter(cmd);
SQLiteDataAdapter adapter;
try
{
cmd.CommandText = "SELECT * FROM teklif";
adapter = new SQLiteDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
}
catch (Exception ex)
{
Console.WriteLine("Retrieval of Table Failed. " + ex.Message);
return -1;
}
If that fails then make sure that is the correct table name in your sqlite database.

Related

How to search between 2 dates on access database vs?

I'm trying this code but it shows an error on da.Fill(dt)
No value given for one or more required parameters.
Why does it show that error? I clearly check all names of databases and tables and fields, they all are correct and I'm using date/time field for datetime.
Can you help me with this?
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb";
OleDbConnection ccc = new OleDbConnection(conn);
ccc.Open();
string css = "SELECT * from tbl3 Where dateitem between '" + dateTimePicker1.Value.ToString() + "%' AND '" + dateTimePicker2.Value.ToString()+"%'";
OleDbCommand non = new OleDbCommand(css, ccc);
OleDbDataAdapter da = new OleDbDataAdapter(non);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
As others have mentioned you should use the parameters instead of hard coding the values.
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb"))
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
var param1 = new OleDbParameter("#DateTimePicker1", OleDbType.DBDate); //you may have to play with different types
param1.Value = dateTimePicker1.Value;
cmd.Parameters.Add(param1);
var param2 = new OleDbParameter("#DateTimePicker2", OleDbType.DBDate);
param2.Value = dateTimePicker2.Value;
cmd.Parameters.Add(param2);
cmd.CommandText = "SELECT * from tbl3 Where datetime >= #DateTimePicker1 and datetime <= #DateTimePicker2";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
}
}

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

I want to get data from mysql with respect to date, I have try a code it doesn't work

private void searchbutton_Click(object sender, EventArgs e)
{
myconnectionstring = "DataSource=127.0.0.1;Database=highlandsmartapp;username=root;password=";
connection = new MySqlConnection(myconnectionstring);
connection.Open();
try
{
MySqlDataAdapter sd = new MySqlDataAdapter(
"SELECT * FROM highlandsmartapp.order WHERE order_date BETWEEN'"
+ DateTimePicker1.Value.ToString()
+ "'AND'" + DateTimePicker2.Value.ToString() + "' ", connection);
DataTable dt = new DataTable();
sd.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
DataGridView.DataSource = bsource;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your code you concatenate together strings to form your sql command. When converting the date from the DateTimePicker value you ask the framework to convert do that but the framework converts the dates according to the local convention for your culture.
This is very often not what the database expects and you get nothing in return (and you are lucky if you don't get any exception)
Instead you should pass the DateTime values as parameters and let the database figure it how to use those values without any kind of conversion
MySqlDataAdapter sd = new MySqlDataAdapter(
#"SELECT * FROM highlandsmartapp.order WHERE order_date BETWEEN #dp1 AND #dp2", connection);
sd.SelectCommand.Parameters.Add("#dp1", MySqlDbType.Date).Value = DateTimePicker1.Value.Date;
sd.SelectCommand.Parameters.Add("#dp2", MySqlDbType.Date).Value = DateTimePicker2.Value.Date;
DataTable dt = new DataTable();
sd.Fill(dt);
....

How duplicate entries be prevented while using SqlBulkCopy?

I am importing excel data into sql server using SqlbulkCopy, but the problem is i want to prevent any duplicate records being entered. Is there a way by which duplicate can be ignored or deleted automatically?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
var command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch
{
}
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable";
r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
Can this problem be fixed by creating a trigger to delete duplicates? if yes how? i am a newbie i have never created a trigger.
Another problem is no matter what i try i am unable to get column mapping to work. I am unable to upload data when column names in excel sheet and database are different.
You can create INDEX
CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY
And when you will insert data with bulk to db, all duplicate values will not inserted.
no, either you manage it on your dr object on you code before you load it into the db (like running a DISTINCT operation) or you create a trigger on the DB to check. The trigger will reduce the bulk insert's performace though.
Another option would be to bulk insert into a temp table and then insert into your destination table FROM your temp table using a select DISTINCT
as far as I remember,
you could filter out the redundant rows when importing from the excel file itself.
the following SQL query should be used in the OleDbCommand constructor.
var command = new OleDbCommand("Select DISTINCT ID,Data FROM [Sheet1$]", connection);

unable to display data using parametrized query with c#

I am trying to display the data using parametrized query
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes ";
xconn.Open();
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(s,xconn);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
How do I get it to work?
Try this:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes";
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
You don't need to call SqlConnection.Open() when you are using the SqlDataAdapter.Fill() method. In that method it opens up the connection and disposes/closes it when complete. (this isn't the problem, just an FYI)
The way you created your SqlDataAdapter is the problem. You didn't create it with the SqlCommand as a constructor, just the command text. Because of that, you didn't pass in the parameter that was specified in the SqlCommand class.
Let me know if that works. And if that doesn't work, try manually running this query in SSMS to ensure that it actually returns a result set. Also, make sure that your ListControl.SelectedValue property contains something. Do this by debugging and analyze what is stored there.

Categories

Resources