DataSet Insert into tables - c#

Is that possible to insert into SQL with DataSet input ?
I have created my DataSet like this :
SqlCommand comm_SelectAll = new SqlCommand(sql_SelectAll, connectionWrapper.conn);
comm_SelectAll.Parameters.AddWithValue("#NO_CLIENT", IdClient);
if (Anne != "")
comm_SelectAll.Parameters.AddWithValue("#DATE_PERIMER", Anne);
SqlDataAdapter adapt_SelectAll = new SqlDataAdapter();
adapt_SelectAll.SelectCommand = comm_SelectAll;
DataSet dSet_SelectAll = new DataSet();
adapt_SelectAll.Fill(dSet_SelectAll);
dSet_SelectAll.Dispose();
adapt_SelectAll.Dispose();
Now I want to insert data into SQL table xx, how can I do that ?
Thanks you in advance

You can try like this ...with out using dataset
public static string BuildSqlNativeConnStr(string server, string database)
{
return string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;", server, database);
}
private void simpleButton1_Click(object sender, EventArgs e)
{
const string query = "Insert Into Employees (RepNumber, HireDate) Values (#RepNumber, #HireDate)";
string connStr = BuildSqlNativeConnStr("apex2006sql", "Leather");
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add(new SqlParameter("#RepNumber", 50));
cmd.Parameters.Add(new SqlParameter("#HireDate", DateTime.Today));
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException)
{
System.Diagnostics.Debugger.Break();
}
}

Related

Fetching Data from MySQL and Inserting it in MS SQL SERVER in visual studio c#

Am trying to read a table from a Mysql database and store all of it in a ms sql server in c# am reading from mysql correctly my problem is how to store the data i read in ms sql in the second part of code
string constring= ConfigurationManager.ConnectionStrings["cnxMysql"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0",conn);
conn.Open();
cmd.ExecuteNonQuery();
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt",conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
conn2.Close();
conn.Close();
I have a reverse issue, I have to transfer data from MS SQL Server to MySQL.
I have used below snippet for this, but I personally don't recommend this for production as it adds data one by one row. But you can use it for a small dataset or local environment. You can add a try-catch as well as customize as per your need. This is for just reference.
public void Main()
{
var table = GetDataTableFromSQLServer();
AddToMySQL(table);
}
private DataTable GetDataTableFromSQLServer()
{
var connection = GetSqlServerConnection();
string query = "SELECT Column1, Column2 FROM TableName WHERE Column3 is NOT NULL";
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
connection.Close();
return table;
}
private void AddToMySQL(DataTable table)
{
var connection = GetMySQLConnection();
connection.Open();
string query = "INSERT INTO TableName (column1, column2) VALUES(#column1, #column2);";
int i = 0;
foreach (DataRow row in table.Rows)
{
if (i % 1000 == 0)
{
// Closing & Reopening connection after 1000 records
connection.Close();
connection.Open();
}
Console.WriteLine($"Adding ({++i}/{table.Rows.Count})");
MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.Add(new MySqlParameter("#column1", MySqlDbType.Int64) { Value = row.Field<long>("column1").Trim() });
command.Parameters.Add(new MySqlParameter("#column2", MySqlDbType.VarChar) { Value = row.Field<string>("column2").Trim() });
var affectedRows = command.ExecuteNonQuery();
}
connection.Close();
}
private SqlConnection GetSqlServerConnection()
{
string connectionString = #"Data Source=...";
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
private MySqlConnection GetMySQLConnection()
{
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder
{
Server = "...",
Database = "...",
UserID = "...",
Password = "...",
Port = 3306
};
MySqlConnection connection = new MySqlConnection(connectionBuilder.ToString());
return connection;
}
Refer below code, you can optimize this code as there is alot of space for optimization but this is simple for beginner to understand basic level:
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0", conn);
conn.Open();
DataSet data;
using (MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(mySqlCommand))
{
data = new DataSet();
sqlAdapter.Fill(data);
}
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
conn2.Open();
for (int i = 0; i < data.Tables[0].Rows.Count; i++)
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt(column1,column2) values(#col1,#col1)", conn2);
cmd2.Parameters.AddWithValue("col1", data.Tables[0].Rows[i][0].ToString());
cmd2.Parameters.AddWithValue("col12", data.Tables[0].Rows[i][1].ToString());
cmd2.ExecuteNonQuery();
}
conn2.Close();
conn.Close();

How to retrieve data from database in label

I wanat to retrieve student ID from database. Here is my code what i have tried but it is not displaying anything.
Thanks...
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
string str = "select * from StRecords where StID='" + Session["login"] + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label11.Text = dt.Rows[0]["StID"].ToString();
}
}
If you want to take just StudentId from the database, then you just select that column and use ExecuteScalar property.
Code
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
{
con.Open();
string str = "select [StID] from StRecords where StID = #stdId;";
using (SqlCommand com = new SqlCommand(str, con))
{
com.Parameters.AddWithValue("#stdId", Session["login"]);
Label11.Text = com.ExecuteScalar().ToString();
}
}
}
Also always use parameters instead passing the value in single quotes to avoid SQL injection attack.
Also try to give the connection string in Web.Config file.

Load data Oracle Table to C# combobox using Oledb

hello i have create a table buy_unit in oracle database
CREATE TABLE buy_unit(
unit_id NUMBER(10) not null PRIMARY KEY,
unit_name VARCHAR2(10) not null
);
and insert Values
INSERT INTO BUY_UNIT
values(001,'Liter');
desc SELL_BUY_UNIT;
then create a combo box combobox1 in C# now can load buy_unit table data in combobox ? i have use the connection:
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=XE;User ID=user1;password=pssword");
Well, you can see below code which is refering SQLConnection. You can change as per your DB may be OracleConnection or so. While using SQL, we have pass connection string with UID and PWD.
For Oracle
have connection string as
string con = "Data Source=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST = 000.00.0.00)(PORT = 0000)))(CONNECT_DATA =(SERVICE_NAME = database)));User ID=User/Schema;Password=password;Unicode=True";
public void BindComboBox()
{
SqlConnection con = new SqlConnection(#"server=ServerName; database = DBName ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select desire column from table";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "name to display";
cbSupportID.ValueMember = "id";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
and try to use using block when you open DB connection as below
using (OracleConnection objConn = new OracleConnection(con))
{
\\ you code
\\ do your stuff
}
Code for Oracle. Excuse for syntax.
public void Fillcombo()
{
string oradb = " Data Source=xe;User Id=dbname;Password=pws; ";
string query = "select id , name from table";
OracleConnection condatabase = new OracleConnection(oradb);
OracleCommand cmddatabase = new OracleCommand(query, condatabase);
try
{
condatabase.Open();
OracleDataReader myReader = cmddatabase.ExecuteReader(); ;
myReader = cmddatabase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetInt32(0).ToString();
comboBox1.Items.Add(sname.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Why Datatables return Null when it is executed via SQL Command text?

I got two classes, one for db connection and another to get data. When I use the SqlCommand type as stored procedure it returns the data table properly, but when I change the command type to text and change the command text properly it returns a null value. Why is this happening?
Class 1
public class DB_Connection
{
public SqlConnection cnn;
public SqlCommand cmd;
public SqlDataAdapter ada;
public DB_Connection()
{
cnn = new SqlConnection("Data Source=svr01;Initial Catalog=PDFScramble;Integrated Security=True");
cnn.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;// *changed in here SP or Text*
cmd.Connection = cnn;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
}
Class 2
public class Data : DB_Connection
{
public string DException { get; set; }
public DataTable Datatable { get; set; }
public bool GetCivicEntities()
{
try
{
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
ada.Fill(Datatable);// *Null in here*
return true;
}
catch (Exception ex)
{
DException = ex.Message;
return false;
}
}
Your Datatable is null, because of that you have this problem. This should fix it.
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
Datatable = new DataTable();
ada.Fill(Datatable);
return true;
There is something wrong with the class structure. Check with this
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("SPName", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("select * from dummy",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

Categories

Resources