I'm executing an sql query through C# to fetch XML data as follows, but in the string getxml_string the XML data is not complete as compared to the data on SQL server, I feel I'm doing something wrong with the getxml_string, but can't figure out:
string getxml = "some query"
DataTable getxml_table = SQLClass.GETSQL(getxml , conn);
var doc = new XmlDocument();
string getxml_string = getxml_table.Rows.OfType<DataRow>().Select(x => x[0].ToString()).First();
doc.LoadXml(getxml_string);
In GETSQL it's nothing fancy just as follows:
public static DataTable GETSQL(string sqller, SqlConnection connection)
{
DataTable data_table = new DataTable();
connection.Open();
using (SqlCommand command = new SqlCommand(sqller, connection))
{
SqlDataAdapter adapter = new SqlDataAdapter(command );
adapter.Fill(data_table);
connection.Close();
return data_table ;
}
}
This worked for me:
List<datarow> list = getxml_table.AsEnumberable().ToList();
Related
The following C# code runs a DAX statement and retrieves a DataTable. This works fine, but now I need to retrieve from the database up to N rows. Is there a way to limit the number of rows returned by the Fill function? If not, how can I retrieve the top N rows? Note that I need to keep this generic for any DAX statement, so you shouldn't change the DAX itself. Also, I don't want to retrieve all the data and then take the first N rows as the data may be too large.
public static DataTable runDaxStatement(int maxRows) {
var con = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
AdomdConnection conn = new AdomdConnection(con);
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
AdomdCommand cmd = new AdomdCommand("evaluate customers", conn);
AdomdDataAdapter da = new AdomdDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
Came across the following TOPN function in the documentation.
This can be used to return the top N rows of the specified table.
For example
public static DataTable runDaxStatement(int maxRows) {
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
using(AdomdConnection connection = new AdomdConnection(connectionString)) {
string commandText = $"EVALUATE TOPN({maxRows}, customers, <orderBy_expression_here>)";
AdomdCommand command = connection.CreateCommand();
command.CommandText = commandText;
DataSet dataSet = new DataSet(){
EnforceConstraints = false
}
AdomdDataAdapter adapter = new AdomdDataAdapter(command);
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}
As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.
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
My Web Service are going to create in-memory sqlite from sql-server DB.
since i want my data not stored localy due to security restriction
im using in-memory method.
this my DB creator code :
public ActionResult Get()
{
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
{
try
{
var sqlAdapter = new SqlDataAdapter("SELECT ID,Code,Name FROM UserDB", connection);
DataTable table = new DataTable();
sqlAdapter.AcceptChangesDuringFill = false;
sqlAdapter.Fill(table);
var sqlliteconnection = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;");
sqlliteconnection.Open();
string sql = "create table UserDB(ID INTEGER,Code TEXT, Name TEXT)";
SQLiteCommand command = new SQLiteCommand(sql, sqlliteconnection);
command.ExecuteNonQuery();
var sqliteAdapter = new SQLiteDataAdapter("SELECT * FROM Kiosk", sqlliteconnection);
var cmdBuilder = new SQLiteCommandBuilder(sqliteAdapter);
sqliteAdapter.Update(table);
DataTable table_sqlite = new DataTable();
sqliteAdapter.Fill(table_sqlite);
}
catch (Exception ex)
{
}
}
return """My in-memory Database.3db """
}
now i want to to get copy of in-memory db when i call the get() ActionResult.
I created win forms, and I wanna insert sql commands and get data from database. If I put query directly into code sql commands, everything is ok, if I put query by textbox I have a lot of bugs like:
$exception {"Could not find stored procedure 'select * from uczniowie'."}
System.Exception {System.Data.SqlClient.SqlException }
this {MateuszLab4.connectDB} MateuszLab4.connectDB
question "\"select * from uczniowie\"" string
dataTable {} System.Data.DataTable
sqlDataReader null System.Data.SqlClient.SqlDataReader
sqlCommand {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
Here is my code:
private void buttonSearch_Click(object sender, EventArgs e)
{
string query = textBoxQuery.Text;
connectDB databaseWin = new connectDB("(localdb)\\v11.0", "Mat");
dataGridViewAdvanced.DataSource = databaseWin.DataDownload(query);
}
When I put into string query sql commands (for example string query = "select * from students" ) everything is working very well. If I replaced with data from textbox sth is wrong. Could you give me some tips guys?
here is my class with datadownloada:
public DataTable DataDownload(string question)
{
DataTable dataTable = new DataTable();
SqlDataReader sqlDataReader;
SqlCommand sqlCommand;
sqlCommand = new SqlCommand(question);
sqlCommand.Connection = this.DBconnection;
sqlDataReader = sqlCommand.ExecuteReader();
dataTable.Load(sqlDataReader);
return dataTable;
}
Try this code.
public DataTable DataDownload(string question)
{
using (var ada = new SqlDataAdapter(question, DBconnection))
{
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}