Import All Access Table Data Into SQL Server Table - c#

I am needing to take all of my access tables and create the exact same table in SQL Server 2008 with data and keys/constraints. The below syntax will insert data if the table already exists, but how do I do it if the table does not exist? Or is there a better method programmatic ally in play to already achieve this result?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccessToSQL
{
public partial class Form1 : Form
{
const string databaselocation = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
List<string> tables = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetTableNames();
const string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
const string connectionStringDest = "Data Source = TO\\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=SSPI;";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
foreach (string tbl in tables)
{
var commandSourceData = new OleDbCommand("Select * from "+tbl, sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = "dbo."+tbl;
try { bulkCopy.WriteToServer(reader); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { reader.Close(); }
}
}
}
}
}
public List<string> GetTableNames()
{
try {
using (OleDbConnection con = new OleDbConnection(databaselocation))
{
con.Open();
//DataTable schema = con.GetSchema("Columns");
//foreach (DataRow row in schema.Rows)
//{
// tables.Add(row.Field<string>("TABLE_NAME"));
//}
foreach (DataRow r in con.GetSchema("Tables").Select("TABLE_TYPE = 'TABLE'"))
{
tables.Add(r["TABLE_NAME"].ToString());
}
return tables;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
return tables;
}
}
}

Related

ADO.NET connection to SharePoint List causing memory leak

I am connecting to a SharePoint list using the following code. The problem is that if I run a Command, the console application hangs and doesn't close. I can see that the application is still consuming memory. Without a Command, the debugger exits cleanly.
I am also looking for a way to connect to SharePoint with EntityFramework, or a more modern way that doesn't use the SharePoint API.
The sample uses several methods to connect to the same SharePoint list.
namespace TestADO
{
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using ADODB;
internal class Program
{
public static string ConnectionStringBase = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes;Pooling=false;DATABASE=https://.../sites/...;LIST={xxxxxxx-ac0a-4cb3-8a32-ecbdxxxxxxxx}";
public static string sql = "select top 10 * from [Call Distributions]";
static void Main(string[] args)
{
ADONetImplementationWithAdapter();
ADONetImplementation();
}
static void ADONetImplementationWithAdapter()
{
OleDbDataAdapter oledbAdapter;
using (OleDbConnection conn = new OleDbConnection(ConnectionStringBase))
{
DataSet ds = new DataSet();
conn.Open();
oledbAdapter = new OleDbDataAdapter(sql, conn);
oledbAdapter.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
Console.WriteLine(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
conn.Close();
}
}
static void ADONetImplementation()
{
using (OleDbConnection conn = new OleDbConnection(ConnectionStringBase))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2));
}
reader.Close();
cmd.Dispose();
}
conn.Close();
}
}
static void ADOImplementation()
{
Connection connection = new Connection();
connection.CursorLocation = CursorLocationEnum.adUseServer;
connection.ConnectionString = ConnectionStringBase;
connection.Open();
object res;
var rst = connection.Execute(sql, out res);
while (!rst.EOF)
{
rst.MoveNext();
}
rst.Close();
rst = null;
//Recordset recordset = new Recordset();
//recordset.Open(sql, connection, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic);
//recordset.Close();
//recordset = null;
connection.Close();
connection = null;
}
}
}
Please try to use the following code to connect to SharePoint:
using Microsoft.SharePoint.Client;
using System;
using System.Linq;
using System.Security;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string siteCollectionUrl = "https://globalsharepoint2020.sharepoint.com";
string userName = "YourSPOUserName#yourtenant.onmicrosoft.com";
string password = "YourSPOPassword";
Program obj = new Program();
try
{
obj.ConnectToSharePointOnline(siteCollectionUrl, userName, password);
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
}
}
public void ConnectToSharePointOnline(string siteCollUrl, string userName, string password)
{
//Namespace: It belongs to Microsoft.SharePoint.Client
ClientContext ctx = new ClientContext(siteCollUrl);
// Namespace: It belongs to System.Security
SecureString secureString = new SecureString();
password.ToList().ForEach(secureString.AppendChar);
// Namespace: It belongs to Microsoft.SharePoint.Client
ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);
// Namespace: It belongs to Microsoft.SharePoint.Client
Site mySite = ctx.Site;
ctx.Load(mySite);
ctx.ExecuteQuery();
Console.WriteLine(mySite.Url.ToString());
}
}
}

Unable to display image on DataGridView from Microsoft Access

I am storing data from MS Access database in DataTable and then displaying it on DataGridView.
All the columns are showing except the image column. I have stored the image in the database as "OLE Object". I want to display image in the last column, though when the form loads I get error:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace ShowDataInDatagridviewFromAccessDatabase
{
public partial class Form1 : Form
{
OleDbConnection acceddDatabaseConnection = null;
string connectionSttring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Authentic\Documents\Database1.accdb";
string sqlQuery = "SELECT * FROM Table1";
public Form1()
{
acceddDatabaseConnection = new OleDbConnection(connectionSttring);
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
acceddDatabaseConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, acceddDatabaseConnection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (acceddDatabaseConnection != null)
{
acceddDatabaseConnection.Close();
}
}
}
}
}
//Function for retrieving data from ms access database and displaying it on DataGridView
public void populateDataGridView()
{
//First, clear all rows before populating datagridview with data from MS Access Database. Check if datagridview rows are empty before clearing.
if (dataGridView1.Rows.Count > 0)
{
dataGridView1.Rows.Clear();
}
try
{
accessDatabaseConnection.Open();
//OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, acceddDatabaseConnection);
OleDbCommand command = new OleDbCommand(selectDataFromMSAccessDatabaseQuery, accessDatabaseConnection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[8].GetType());
dataGridView1.Rows.Add(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader[5].ToString(), reader[6].ToString(), reader[7].ToString(), (byte[])reader[8]);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
//Finally Close MS Access Database Connection
if (accessDatabaseConnection != null)
{
accessDatabaseConnection.Close();
}
}
}
Source :
http://mauricemuteti.info/how-to-connect-to-access-database-and-display-data-and-images-in-datagridview-in-c-sharp-windows-application/

How to save data to Service-based Database in Visual Studio

I have a local Db named NumLeter.mdf whit two tables: LeterTb and NumberTb. I want to insert in NumberTb new values, when the application is running the new values that I inserted show to me correctly as if they had been inserted, but when close the application and clic in Show Table Data the new data was not added in the table. I have instaled EntityFramework v:6.1.3. This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LearningVS
{
public partial class Form1 : Form
{
SqlConnection conexion;
public Form1()
{
InitializeComponent();
conexion = cConexion.getConexion();
}
private void btInsertNum_Click(object sender, EventArgs e)
{
insertNumber();
}
public void insertNumber()
{
SqlCommand command = new SqlCommand();
command.Connection = conexion;
command.CommandText = "INSERT INTO NumberTb(numberA, numberB, numberC) VALUES(#numberA, #numberB, #numberC)";
command.Parameters.Add("numberA", SqlDbType.Int, 3).Value = this.txNumberA.Text;
command.Parameters.Add("numberB", SqlDbType.Int, 3).Value = this.txNumberB.Text;
command.Parameters.Add("numberC", SqlDbType.Int, 3).Value = this.txNumberC.Text;
command.ExecuteNonQuery();
//testing this either
/*SqlDataAdapter datAdapt = new SqlDataAdapter(command);
NumLeterDataSet dtSet = new NumLeterDataSet();
datAdapt.FillSchema(dtSet, SchemaType.Source, "NumberTb");
datAdapt.Fill(dtSet, "NumberTb");
datAdapt.Update(dtSet.NumberTb);*/
}
//Also I tried by creating ADO.NET Entity Data Model whit the same result
private void button1_Click(object sender, EventArgs e)
{
using (var db = new NumDbModel())
{
var numbers = new NumberTb()
{
numberA = 22,
numberB = 33,
numberC = 44,
};
db.NumberTBs.Add(numbers);
db.SaveChanges();
}
}
}}
this is where I handle the connection
namespace LearningVS
{
class cConexion
{
private static SqlConnection conexion;
public static SqlConnection getConexion()
{
if (conexion != null)
{
return conexion;
}
conexion = new SqlConnection(Properties.Settings.Default.NumLetersConnectionString);
try
{
conexion.Open();
return conexion;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error de conexión" + e.Message);
return null;
}
}
public static void cerrarConexion()
{
if (conexion != null)
{
conexion.Close();
}
}
}}

C# Configuration Manager Connection String

So I am trying to do an application that makes a simple transaction from account 1 to account 2
here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Transactions;
namespace BankTransactions
{
public class Transactions
{
public bool Transfer(int fromAcno, int toAcno, decimal amt)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
cn.Open();
SqlTransaction trans;
trans = cn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("update PSBank set amount=amount+{0} where accountno={1}", amt, toAcno);
cmd.ExecuteNonQuery();
cmd.CommandText = String.Format("update PSBank set amount=amount-{0} where accountno={1}", amt, fromAcno);
cmd.ExecuteNonQuery();
decimal balance;
balance = (decimal)cmd.ExecuteScalar();
decimal originalBalance;
originalBalance = balance - amt;
bool flag = true;
if (originalBalance >= 5000)
{
trans.Commit();
flag = true;
}
else
{
trans.Rollback();
flag = false;
}
cn.Close();
return flag;
}
catch (Exception ex)
{
return false;
}
}
}
}
and here is the winform code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BankTransactions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int fromAcno = int.Parse(txtFromAcno.Text);
int toAcno = int.Parse(txtToAcno.Text);
decimal amount = decimal.Parse(txtAmount.Text);
Transactions obj = new Transactions();
if (obj.Transfer(fromAcno, toAcno, amount) ==true)
{
MessageBox.Show("Amount transferred succesfully!", "Confirm");
}
else
{
MessageBox.Show("Error!", "Error");
}
}
}
}
The form has 3 text boxes: txtFromAcno, txtToAcno and txtAmount.
I have the database called NORTHWND with the table PSBank where I have these two accounts.
I am getting the error message, not "amount transferred successfully". I am not sure how to make the connection to the DB in the connection string.
string cs = ConfigurationManager.ConnectionStrings["Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"].ConnectionString;
How do I format it properly?
Put the connection string in app.config like so:
<connectionStrings>
<add name="MyConnection"
connectionString="Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"
providerName="System.Data.SqlClient" >
</connectionStrings>
And then reference it by name in code:
string cs = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Insert records in oracle database using c# odbc

I am messing around in C# trying to understand how to insert records into a database using C# ODBC. I have learned how to read in records to a DGV, but now I am getting stuck on inserting.
The quick overview of what my code is doing, its reading in 20 rows from a table into a DGV, then after that it should insert the same rows into a different table.
I am using VS 2012 and SQL Developer (Oracle).
Here is the code in my Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int rows = 0; rows < 20; rows++)
{
dataGridView1.Rows.Add(); // adding needed amount of rows
for (int cols = 0; cols < 13; cols++)
{
this.dataGridView1[cols, rows].Value = getNumberOfThreads(rows, cols);
}
}
StringBuilder sql = new StringBuilder();
sql.AppendLine("insert into chsarp_test_table");
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
//using (DataTable dt = Database.GetData(sql.ToString()))
// if (dt.Rows.Count > 0)
// Database dt = new Database.SetData(sql.ToString());
Database.SetData(sql.ToString());
}
public static string getNumberOfThreads(int i, int j)
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
using (DataTable dt = Database.GetData(sql.ToString()))
if (dt.Rows.Count > 0)
return dt.Rows[i][j].Equals(DBNull.Value) ? "null" : dt.Rows[i][j].ToString();
return "null";
}
}
}
Here is the code from my Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Odbc; //used for the ODBC stuff
using System.Data; // Used for public static datatable
using System.Windows.Forms;
namespace WindowsFormsApplication13
{
class Database
{
private const string connOdbc = "dsn=atlas32;uid=NAME;pwd=XXXX";
private const string cnnOLE = "provider =XXXX;User ID = NAME;password = XXXX; Data Source = XXX Properties=;Persist Security Info=False";
public static DataTable GetData(string Sql)
{
DataTable dt = new DataTable();
try
{
OdbcConnection cnn = GetConnection();
using (OdbcDataAdapter da = new OdbcDataAdapter(Sql, cnn))
{
da.SelectCommand.CommandTimeout = 0;
da.Fill(dt);
}
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, Sql);
MessageBox.Show("Error 1");
}
return dt;
}
public static void SetData(string sql)
{
try
{
OdbcConnection cnn = GetConnection();
using (OdbcCommand cmd = new OdbcCommand(sql, cnn))
cmd.ExecuteNonQuery();
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, sql);
MessageBox.Show("Error 2");
}
}
private static OdbcConnection GetConnection()
{
try
{
OdbcConnection cnn = new OdbcConnection() { ConnectionString = connOdbc };
cnn.Open();
return cnn;
}
catch (Exception ex)
{
//throw ex;
}
return null;
}
private static void CloseConnection(OdbcConnection Connection)
{
try
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
}
catch (Exception ex)
{
//throw ex;
}
Connection = null;
}
}
}
I tried to step through the code and it goes down in the SetData Method on the ExecuteNonQuery. I tried to look into this but couldnt mind any information that helped me, any push in the right direction would be greatly appreciated.
I was missing the Schema on the table I was inserting on. found this out with the help of #stuartd in the comment section of the question.

Categories