OdbcConnection turns DATE column into STRING? - c#

UPDATE: this happens with OdbcConnection but goes away with SqlConnection. Is there any way to read a "date" via OdbcConnection?
I have a Sql Server database table with a "date" and a "datetime" column. Whenever I use C# ODBC, it returns the Date column as a string. But I would rather it return the Date as a DateTime. Is there any way to make that happen?
string sql = "select dateColumn, dateTimeColumn from Test_Table";
string dsn = "Driver={SQL Server};Server={...};Database=...;Trusted_Connection=True;";
using (OdbcConnection conn = new OdbcConnection(ConfigManager.GetLoansDatabaseDSN()))
{
conn.Open();
OdbcCommand command = new OdbcCommand()
{
Connection = conn,
CommandText = sql
};
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable table = ds.Tables[0];
//The type of "dateColumn" is now string not DateTime
}
}

One of two ways.
Cast your dateColumn to a DateTime
string sql = "select Convert(DateTime, dateColumn) as dateColumn, dateTimeColumn from Test_Table";
Build your DataTable manually to include the columns type.

Related

How do I return a table from a SQL query as a List in C#?

I have a Xamarin app that connects to a SQL Server (*), and I want to insert the data from the SQL Server's tables into a local SQLite database. My approach is to execute a query like
select * from Table1
retrieve the results of the query as a List, then insert that List into my SQLite table. That said I'm very new at using SqlClient, so please share if there are better ways to do this. Thanks.
Edit: the smallest number of columns these tables have is 5. Don't know if that disqualifies Lists as the best option.
My code:
private void LoadData()
{
string cs = #"connection string here";
using (SqlConnection sconn = new SqlConnection(cs))
{
sconn.Open();
SqlDataReader reader = null;
SqlCommand aml = new SqlCommand("select * from Table1");
reader = aml.ExecuteReader();
while (reader.Read())
{
// get result of query as List somehow?
}
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<Table1>();
if (conn.Query<Table1>("select * from Table1").Count() <= 0)
{
// insert the list object
}
}
}
}
(*) The app does not use a web service as the app is intended for onsite use only and will not be distributed publicly.
A better alternative way to do it more easier is to use a ORM like dapper
With the help of dapper, all you need to do is
using (var connection = new SqlConnection(_sqlConnectionString))
{
var results = connection.Query<YourTableModel>(query).ToList();
return results;
}
You can get data from the SQL Server as DataTable or convert it to a list as you prefer.
public DataTable GetDataTable(string connectionString, string tableName)
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string query = $'SELECT * FROM [{tableName}]';
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
Then use this table or list returned from the above method to insert in the SQLite table.
string cs = #"Data Source=datasource;Initial Catalog=databasename;User ID=user;Password=password";
DataTable table = GetDataTable(cs, "Table1");
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<Table1>();
if (conn.Query<Table1>("select * from Table1").Count() <= 0)
{
foreach(DataRow row in table.Rows)
{
//Access values of each row column row["columnName"]
// insert the list object
}
}
}
Refer to this one:
Inserting Data from SQL Server to Sqlite

C# reading values from datatable filled with sql select

I am coding win form app, which checks on startup right of the currently logged user. I had these right saved in MS SQL server in the table. When importing data to Datatable, there is no problem. But when I want to read value, there is message "cannot find column xy".
SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);
DataTable dtRights = new DataTable(); //this is creating a virtual table
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
I would like, that program would save the value from SQL to int.
You are assuming that you have rows being returned, would be my first guess. You should loop through your DataTable instead of simply trying to access element 0 in it.
DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
Object cellValue = row[1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
}
using (SqlConnection con = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = #user"))
{
cmd.Parameters.AddWithValue("#user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
con.Open();
int right = Convert.ToInt32(cmd.ExecuteScalar());
}
}

C# Updating mySQLDateTime Datatable

I'm having trouble updating a mySQL database with a datatable. I can do it with an INSERT statement, but the table fails the assignment when I insert a row with the error "Couldn't store <...> in date Column. I have millions of records to insert and I thought this way might be faster. I actually don't care about the time, just the date.
MySqlConnection con = new MySqlConnection();
con.ConnectionString = string.Format(#"server={0};userid={1};password={2};database={3};AllowZeroDatetime=True", srvr, user, pass, db);
MySqlCommand cmnd = new MySqlCommand();
cmnd.Connection = con;
con.Open();
cmnd.CommandText = "DROP TABLE IF EXISTS dateTest";
cmnd.ExecuteNonQuery();
cmnd.CommandText = "CREATE TABLE dateTest (date DATE, dateTime DATETIME)";
cmnd.ExecuteNonQuery();
string myDate = "2014-04-19";
string myDateTime = "2014-04-20 00:00:00";
//this code works
cmnd.CommandText = string.Format("INSERT INTO dateTest(date, dateTime) VALUES('{0}', '{1}')", myDate, myDateTime);
cmnd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * from dateTest", con);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
DataTable tbl = new DataTable();
da.Fill(tbl);
foreach (DataRow row1 in tbl.Rows)
{
Debug.WriteLine(string.Format("{0} : {1}", row1["date"], row1["dateTime"]));
//returns: 4/19/2014 : 4/20/2014 12:00:00 AM
}
DataRow row2 = tbl.NewRow();
row2["date"] = myDate; //Errors here: Couldn't store <2014-04-19> in date Column. Expected type is MySqlDateTime.
row2["dateTime"] = myDateTime; //Also errors here: Couldn't store <2014-04-20 00:00:00> in dateTime Column. Expected type is MySqlDateTime.
tbl.Rows.Add(row2);
da.Update(tbl);
this is my first time trying to answer a question. Hope this help.
I think you have to convert the date to DateTime first before you can store it in mysql.
string myDateTime = "2014-04-20 00:00:00";
DateTime myDateTimeValue = DateTime.Parse(myDateTime);
Then
row2["dateTime"] = myDateTimeValue;
I have not tried it yet. Hope it works

Column <column name> does not belong to table <table name>

I have a method working with dataset,
var EmpNameList = new List<string>();
var EmpDS = GetEmployeeList();
foreach (DataRow EmpDR in EmpDS.Tables[0].Rows)
{
EmpNameList.Add(EmpDR["EmpName"].ToString()); // Error on this line
}
exception Details:
Column 'EmpName' does not belong to table 'EmpDetailTbl'
at System.Data.DataRow.GetDataColumn(String columnName)
at System.Data.DataRow.get_Item(String columnName)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
at times we also get the following exception for the same method
Cannot find table 0 at System.Data.DataTableCollection.get_Item(Int32 index)
All the above exception are not reproduced consistently and it is intermittent.
The GetEmployeeList definition looks as below
public DataSet GetEmployeeList()
{
var Connectionstring = "MyConnectionString";
var query = "Select EmpName, EmpId, HireDate from EmpDetail";
DataSet ds = new DataSet();
using (OleDbConnection connection = new OleDbConnection(Connectionstring))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds,"EmpDetailTbl");
return ds;
}
}
I have tried with SQL Server using the SqlConnection class also.
This seems to be wierd huh???
If you are filling other DataTables in the DataSet then "EmpDetailTbl" may not be the first one every time (0). Refer to the DataTable by name:
foreach (DataRow EmpDR in EmpDS.Tables["EmpDetailTbl"].Rows) {
http://msdn.microsoft.com/en-us/library/y4b211hz(v=vs.110).aspx
Check out the remarks - if the actual query string you're using returns no rows, no tables are added to the dataset. Also note that the strings used are case sensitive.

Import Data from Excel to Sql Server 2008 #2

string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName);
//Save File as Temp then you can delete it if you want
FileUpload1.SaveAs(path);
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = #conn;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName ="Table1";
bulkCopy.WriteToServer(dr);
Label1.Text = "The Client data has been exported successfully from Excel to SQL";
}
}
}
I am trying to import data from excel to SQL Server, it works fine till I am not passing date but now I want to pass the date to SQL Server it provides error as datatype not matches.
Anyone has logic or please suggest me what can I do to ..
Might be the column in the Excel Sheet is not in a valid date format.
Change it to Date Type.
Select the Column in the Excel Sheet -> Right Click -> Format Cells ->
Number Tab -> Select Date -> Choose your desired Type -> Ok
Then you try to Import...
The DateTime you read from excel is OLE Automation date and you have to convert it to c# DateTime before you insert in to sql server. It would be double value for date when you read from excel. You can use DateTime.FromOADate to convert the double value to DateTime. You can use SqlBulkCopy.WriteToServer(DataTable table), this method allows you to pass the datatable. You can change the date in datatable in require format and use it to save bulk data in sql server. You can import excel data to datatable, this article will help you.
DateTime dt = DateTime.FromOADate(double.Parse(stringVariableContainingDateTime));
It works i tried to convert it in datatble den change datatype and then insert
string sqlConnectionString = #conn;
command.CommandType = CommandType.Text;
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[0][5].ToString() != "")
{
DateTime dt1 = cf.texttodb(dt.Rows[0][5].ToString());
dt.Rows[i][5] = dt1;
}}
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Tablename";
bulkCopy.WriteToServer(dt);
Label1.Text = "The Client data has been exported successfully from Excel to SQL";
}
in this i had created a function txtdob which converts my string to datetime format
Thank you
i tried it workes if u feel so mark it as answer

Categories