C# Transfer Data from ODBC Database to Local SQL Database - c#

I have connected to a DB through an ODBC connection. The data is on a server and I have the appropriate permissions and username/password.
I am trying to import some of the data into a local SQL database (.mdf). I suspect my SQL statement is wrong.
The idea is that when a an item is selected from a listBox that the data will be downloaded to the SQL database.
This has completely stopped any progress on my project. Please help!!!
public partial class frmNorth : Form
{
// variables for the connections
private OdbcConnection epnConnection = new OdbcConnection();
private SqlConnection tempDbConnection = new SqlConnection();
public frmNorth()
{
InitializeComponent();
// This is for the ePN DB
epnConnection.ConnectionString = #"Dsn=ePN; uid=username; pwd=myPa$$Word";
// This is for the local DB
tempDbConnection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TempDB.mdf;Integrated Security=True";
}
private void lbxFSR_SelectedIndexChanged(object sender, EventArgs e)
{
try //For ePN
{
//This is where I need the help <--------------------
epnConnection.Open();
tempDbConnection.Open();
OdbcCommand epnCommamd = new OdbcCommand();
epnCommamd.Connection = epnConnection;
string epnQuery = "INSERT INTO " + tempDbConnection + ".tblTemp (FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC) " +
"SELECT PROJ_FNCL_SPLIT.FNCL_SPLIT_REC_ID,PROJ_FNCL_SPLIT.PROJ_ID,PROJ_FNCL_SPLIT.SALES_SRC_PRC " +
"FROM " + epnConnection + ".PROJ_FNCL_SPLIT " +
"WHERE PROJ_ID=" + lbxFSR.Text + "";
epnCommamd.CommandText = epnQuery;
epnCommamd.CommandTimeout = 0;
epnCommamd.ExecuteNonQuery();
epnConnection.Close();
tempDbConnection.Close();
}
catch (Exception ex)
{
epnConnection.Close();
tempDbConnection.Close();
MessageBox.Show("Error " + ex);
}
}
}
This is the error that I get. The error occurs at epnCommamd.ExecuteNonQuery();
Picture of Error Message

I cant comment cause i don't have enough points so i have to put this in answers but do both of your connections actually open? I would also avoid showing passwords in your connection strings on here.

The problem is that you can't in general INSERT into one table using a SELECT from a table on another database in the way that you're attempting. If source and destination tables are on same database server (eg both on Sql Server) you have a shot at INSERT INTO db1.SourceTable ... SELECT ... FROM db2.DestinationTable.
However, since you have source table on ODBC connection and destination on Sql connection, this won't work.
You need to do it in two steps. Download your ODBC table into a C# DataTable, then upload the C# DataTable into your Sql Server table. I can't test against your databases, but I have tested a version of this code on transfers between Microsoft Access database and a Sql Server database
private void lbxFSR_SelectedIndexChanged(object sender, EventArgs e)
{
try //For ePN
{
//This is where I need the help <--------------------
// Break the operation into two parts
// The ODBC & SQL databases can't talk directly to each other.
// 1. Download ODBC table into your C# DataTable
DataTable dt;
epnConnection.Open();
string epnQuery = "SELECT FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC " +
"FROM PROJ_FNCL_SPLIT " +
"WHERE PROJ_ID='" + lbxFSR.Text + "'";
OdbcCommand epnCommamd = new OdbcCommand(epnQuery, epnConnection);
epnCommamd.CommandTimeout = 0;
OdbcDataReader dr = epnCommamd.ExecuteReader();
dt.Load(dr);
epnConnection.Close();
// 2. Upload your C# DataTable to the SQL table
// This select query tells the SqlDataAdapter what table you want to work with, on SQL database
// The WHERE 0 = 1 clause is to stop it returning any rows,
// however you still get the column names & datatypes which you need to perform the update later
string selectQuery = "SELECT FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC " +
" FROM PROJ_FNCL_SPLIT WHERE 0 = 1";
tempDbConnection.Open();
var da = new SqlDataAdapter(selectQuery, tempDbConnection);
var commandBuilder = new SqlCommandBuilder(da);
// The DataAdapter's `Update` method applies the contents of the DataTable `dt` to the table specified in the `selectQuery`.
// It does this via the SqlCommandBuilder, which knows how to apply updates to a Sql Database.
da.Update(dt); // Channel the C# DataTable through the DataAdapter
tempDbConnection.Close();
}
catch (Exception ex)
{
epnConnection.Close();
tempDbConnection.Close();
MessageBox.Show("Error " + ex);
}
}

Related

How to save data to database using retrieved ID from datagridview?

I wanted to insert some data to the mysql database using that ID that I have retrieved from datagridview. i am new in programming. can someone please help me? thanks
First you need to download and intall
MySQL ADO.Net connector
it's the official ado.net connector for C# applications. once you intall that you can use ado.net standered data access methods to save data.
basic steps
First create a connection to the my sql data base.
Then create a command object contains the insert command.
then provide the object that contain the so called ID and finalize the command object
then Execute the command against the database.
Sample code
This is the class variables that will be used later
private MySqlConnection connection; // this MySqlConnection class comes with the connector
private string server;
private string database;
private string uid;
private string password;
This will Initialize method will configure the connection with the configuration data
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
this method will open a connection to the database . you should write a C Lose method as well .because it's best practice to always close the connection after you used it
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
This will insert a record to database . query will contains the T-SQL query that runs against the database
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
Hope this will help

How to create a login form using a XAMPP database and C#?

string query = "SELECT * FROM staff";
string mySQLConnectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=workshopdb;sslmode=none";
MySqlConnection databaseConnection = new
MySqlConnection(mySQLConnectionString);
MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
databaseConnection.Open();
MySqlDataReader myReader = commandDatabase.ExecuteReader();
if (myReader.HasRows) //checks whether the table is empty
{
while (myReader.Read()) //reads rows consequently
{
MessageBox.Show(myReader.GetString(0) + " " + myReader.GetString(1) + " " + myReader.GetString(3));
//get strings(x) are columns of the table in the db
}
}
databaseConnection.Close();
}
I used this code but It doesn't recognize the username and password that I entered. Instead of recognizing the entered user it shows all users in the database.
In C#, building platform is .NET. Most of the time we can use MSSQL for DB activities. To Configure we can use MSSQL Server Express. XAMPP runs on Apache server. But for the .NET development we need IIS server. At your end arise conflicts. Do more research abourt what are you doing and get know about the dependent technologies

Querying OLAP Cubes via ASHX Service

I'm using the following code to execute a query in C#:
// Create Connection String
AdomdConnection testConnection = new AdomdConnection("Data Source=*****;User ID=******;Provider=MSOLAP.6;Persist Security Info=True;Impersonation Level=Impersonate;Password=******");
// Test Open
testConnection.Open();
// Make Query
AdomdCommand cmd = new AdomdCommand(#"SELECT { [Measures].[Payment Amount] } ON COLUMNS,
{ [Charging Low Orgs].[Charging Division].[Charging Division] } ON ROWS
FROM [Payments]", testConnection);
AdomdDataReader dataReader = cmd.ExecuteReader();
// Close Connection
testConnection.Close();
And I keep getting this error on the cmd.ExecuteReader() call:
{"XML for Analysis parser: The CurrentCatalog XML/A property was not specified."}
The only literature that I could find that was relavent to this was that the query isn't resolving because impersonation wasn't set, but I specified that in the connection string.
Another article which I don't think is related, said to enable BAM on Excel, but I don't have that option in Excel, and I fail to see how that would make a difference for a web service.
Please help!
The following example includes a catalog parameter in the connection string:
static void Main(string[] args)
{
AdomdConnection conn = new AdomdConnection(
"Data Source=localhost;Catalog=Adventure Works DW Standard Edition");
conn.Open( );
string commandText = "SELECT {[Measures].[Sales Amount], " +
"[Measures].[Gross Profit Margin]} ON COLUMNS, " +
"{[Product].[Product Model Categories].[Category]} ON ROWS " +
"FROM [Adventure Works] " +
"WHERE ([Sales Territory Country].[United States])";
AdomdCommand cmd = new AdomdCommand(commandText, conn);
AdomdDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Blank values in SqlDatasource

After setting up my SqlDataSource on another page to display the values, they come up as 2 blanks for the 2 times I entered test values on the comments page.
I think I'm missing something in getting them into the table in the SQL Server database value?
I'm not sure what information is needed here, so please inform me.
Thanks in advance
EDIT #1 for user request for CODE
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("Data Source=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("Email", txtEmail.Text);
cmd.Parameters.AddWithValue("Comments", txtComment.Text);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
}
EDIT #2
The values seems to be empty for the Name, Phone, Email, and Comments in the database and when I test the query, so I think it's registering the entries, just not taking the values into the SQL?
EDIT #3
Due to a suggestion by coder and rs, I've done what they've said. And now I get this error.
"String or binary data would be truncated. The statement has been terminated."
The code has been updated as well.
EDIT #4
This question is a follow up for SQL Server Error, 'Keyword not supported 'datasource'.
Remove all the "" similar to this txtPhone.Text = ""; before entering values to SQL as Server you're entering null values to that. So even if you give some values to the textbox it takes predefined NULL values and it dosen't enter either of them.

Inserting records permanetly into sql server using c#

I created a database in sql server express edition, in that i create a table called employee. Now i am able to inserting rows(records) dynamically into table successfully, and i can also read those records successfully. But the problem is the values which are inserted dynamically are stored temporarily. When i close and reopen the application the previous inserted records are not available. can u please suggest me what can i do to save records permanently into the database.
thanking you.....
This is my code used to inserting the records into sql server database. Please help me out of this problem...
namespace VACS_practice
{
public partial class Form1 : Form
{
string m_sVehicleNo, m_sName, m_sFlatNo, m_sImagpath;
System.Data.SqlClient.SqlConnection Con;
System.Data.SqlClient.SqlCommand Cmd;
string ConString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VACSDB.mdf;Integrated Security=True;User Instance=True";
public Form1()
{
InitializeComponent();
}
private void btnAddClick(object sender, EventArgs e)
{
Con = new SqlConnection(ConString);
m_sVehicleNo = m_VehicleNo.Text;
m_sName = m_Name.Text;
m_sFlatNo = m_Phno.Text;
//m_sImagpath = m_ImgPath.Text;
Cmd = new SqlCommand("INSERT INTO ResidentDB ([R_VehNo],[R_Name],[R_PhNo]) VALUES ('" + m_sVehicleNo + "','" + m_sName + "','" + m_sFlatNo + "')", Con);
Con.Open();
Cmd.ExecuteNonQuery();
Con.Close();
MessageBox.Show("Inserted successfully");
// this.Close();
}
Almost certainly you are not committing your changes. If you are running transactions then you must commit.
Alternatively, you are making changes in your in-memory versions, that are not connected to the database at all.

Categories