What does SqlCommandBuilder.GetUpdateCommand Create? - sql-server

So if I want to update my DataSource I use
selCmd = New SqlCommand("Select foo from bar", New SqlConnection("baz"))
da = New SqlDataAdapter(selCmd)
cmdB = New SqlCommandBuilder(da)
...'User changes some Data
da.UpdateCommand = cmdB.GetUpdateCommand
da.Update(testDS, "testtable")
Does GetUpdateCommand create its own connection instance or does it use da.SelectCommand.Connection?
Thank you

Related

Linq To Sql Conversation In Wcf Service

Can you please provide an answer following sql query to linq . I have some knowledge about linq but i am confused about sql reader object ..
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
var cmd = new SqlCommand("SELECT Account_Type,Account_Fees,Account_Balance,Over_Draft_Limit FROM Current_Account_Details WHERE Account_Number = '" + accountNumber.Account_Number + "'", conn);
cmd.CommandType = CommandType.Text;
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
accountNumber.Account_Type = reader["Account_Type"].ToString();
accountNumber.Account_Fee = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
First you have to have DbContext which you must instantiate in using(usual practice):
using (DbContext db = new DbContext())
{
var results = (from ad in db.Current_Account_Details
where ad.Account_Number == accountNumber.Account_Number
select ad).ToList();
}
Make sure you have created the object data model from database.
I do not get the other part of your post but this would be the general idea of how to write Linq2Entities queries.

Is Referential integrity between tables mandatory for custom conflict resolver in sql merge replication?

I have a database which have multiple tables but these tables have not any relationship define(Referential integrity) in database.
They are related to each other but maintained by trigger and application.
I have created custom conflict resolver on Microsoft SQL server 2008 R2 merge replication. In custom conflict resolver, I am checking subscribers priority by SQL query from publisher database and based on that priority. I am resolving the conflict in replication data-table.
Custom Conflict Resolver Code as below
public override ActionOnUpdateConflict UpdateConflictsHandler(DataSet publisherDataSet, DataSet subscriberDataSet, ref DataSet customDataSet,
ref ConflictLogType conflictLogType, ref string customConflictMessage, ref int historyLogLevel, ref string historyLogMessage)
{
// Priority column AcceptDate
DateTime? publisherModifiedDate = string.IsNullOrWhiteSpace(Convert.ToString(publisherDataSet.Tables[0].Rows[0]["AcceptDate"])) ? new Nullable<DateTime>() : DateTime.Parse(publisherDataSet.Tables[0].Rows[0]["AcceptDate"].ToString());
DateTime? subscriberModifiedDate = string.IsNullOrWhiteSpace(Convert.ToString(subscriberDataSet.Tables[0].Rows[0]["AcceptDate"])) ? new Nullable<DateTime>() : DateTime.Parse(subscriberDataSet.Tables[0].Rows[0]["AcceptDate"].ToString());
//Get priority via userid
int publisherUserId = Convert.ToInt32(publisherDataSet.Tables[0].Rows[0]["UserId"]);
int subcriberUserId = Convert.ToInt32(subscriberDataSet.Tables[0].Rows[0]["UserId"]);
DataTable dt = new DataTable();
//Publisher
using (SqlConnection sqlConnection = new SqlConnection(AppConfig.PubliosherConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from RISubscriber where UserId=" + publisherUserId, sqlConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
int publisherPriority = Convert.ToInt32(dt.Rows[0]["SubscriberPriority"]);
//Subcriber
dt = new DataTable();
using (SqlConnection sqlConnection = new SqlConnection(AppConfig.PubliosherConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from RISubscriber where UserId=" + subcriberUserId, sqlConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
int subcriberPriority = Convert.ToInt32(dt.Rows[0]["SubscriberPriority"]);
if (subcriberPriority > publisherPriority)
{
customDataSet = subscriberDataSet.Copy();
}
else
{
customDataSet = publisherDataSet.Copy();
}
return ActionOnUpdateConflict.AcceptCustomConflictData;
}
Question: I want to replicate the data between subscribers based on custom conflict resolver and want to maintain the data integrity between tables.
Please let me know. If you have any idea.
How we can do it?
Thank you

How can we use both sql and oracle database connection using one object only

I wants to fetch the data from database using C++.Net. I need to do this irrespective of db used in the system. But i don't want to change my code for each database. I am looking for a solution in C++.Net, please do help..
This is what i have now;
Oracle:
OracleConnection *myOracleConnection;
OracleDataAdapter * myDataAdapter;
DataSet * myDataSet;
myOracleConnection = new OracleConnection(S"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw;");
myOracleConnection->Open();
myDataAdapter = new OracleDataAdapter(S"select dbms_xmlgen.getxml(' select * from SampleTable') from dual ",myOracleConnection);
myDataSet = new DataSet("Sample");
Sql:
`SqlConnection *mySQLConnection;
SqlDataAdapter * myDataAdapter;
DataSet * myDataSet;
mySQLConnection = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
mySQLConnection->Open();
myDataAdapter = new SqlDataAdapter(S"select * from [SampleTable]",mySQLConnection);
myDataSet = new DataSet("Sample");`
i wants to do both connection using one connection object. Is there any idea to achieve this???
I can't give you c++ code, but I can help you how to do it. It will be difficult to do it in one connection, but your can get a DataSet back which will work, and you only have to do the code once.
Create a method will return a DataSet, and pass the query as well as what type of connection should be used, in this method depending on tour connection type you do your query and return your result.
You can also add a connectionstring if you wish.
Something like this (it is c# though)
DataSet GetDataSet(string sqlQuery, ConnectionType connType)
{
DataSet dataset = new DataSet("aDataSet");
using (DataTable table = dataset.Tables.Add("aDataTable"))
{
switch (connType)
{
case ConnectionType.MSSQL:
using (var conn = new SqlConnection("Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw"))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
case ConnectionType.Oracle:
using (var conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw"))
{
using (var cmd = new OracleCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
default:
break;
}
}
return dataset;
}
enum ConnectionType { MSSQL, Oracle }

how to bind datagridview in ado.net

i want to bind datagridview on form load using ado.net "Child list for field Physio_cureTable cannot be created". error iam paste here my code please give me suggestions or help
con = new SqlConnection("Data Source=ADMIN\SQLEXPRESS;Initial Catalog=PhysioCure; Integrated Security=true");
sda = new SqlDataAdapter("select RegisterNo,RegistrationDate,Stimulation,PationName,DateOfBirth,ContactNo,Occupation,Age,Sex,Weight,Chief_Complain,Investigation_Result,PastHistoryAny,Physical_Examination,Ref_By_Doctor,Medications,Prognosis,Electro_Therapy,Neuro_Rehabilitation,Ortho_Rehabilitation,Cardio_Pulmonery_Rehabilitation,Sports_Rehabilitation from Physio_cureTable where Syncoperation <>'D'",con);
ds = new DataSet();
sda.Fill(ds);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Physio_cureTable".ToString();// error coming this line
dataGridView1.DataMember = "Physio_cureTable".ToString();
Physio_cureTable has to be a column name you have binded with the DataGridView
dataGridView1.DataMember = "RegisterNO".ToString();

Listbox and SqlDataReader Issue

I am attempting load employee data from a stored procedure into a listbox in a form load event by ID and assign each with an image. The code above is what I have thus far. So what I'm trying to do here is to fill the listview with data from my data reader.
SqlConnection conn = new SqlConnection(
#"Data Source=MyPC\Test;Initial Catalog=TEST5;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
listView1.Items.Clear();
while (dr.Read())
{
ListViewItem recs = new ListViewItem();
recs.Text = dr["dept_name"].ToString();
recs.Text = dr["emp_first_name"].ToString();
recs.Text = dr["emp_last_name"].ToString();
recs.Text = dr["emp_email"].ToString();
recs.Text = dr["emp_phone"].ToString();
recs.Text = dr["emp_position"].ToString();
recs.Text = dr["emp_address1"].ToString();
recs.Text = dr["emp_address2"].ToString();
recs.Text = dr["emp_city"].ToString();
recs.Text = dr["emp_state"].ToString();
recs.Text = dr["emp_postal_code"].ToString();
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
Thank you in advance.
Your query is currently only returning one fieid:
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
I'm guessing you wanted this:
SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn);
You need to open the connection and close your disposable resources. Your current code is constantly replacing the recs.Text property to the point that the only thing you should see in the list are "emp_postal_code" values. I suspect you are looking for something like this, where you display the user name as the main item of the ListViewItem and then include the other information as SubItems of the item (for when displaying in Detailed view):
listView1.Items.Clear();
using (SqlConnection conn = new SqlConnection(...)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn)) {
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read()) {
ListViewItem recs = new ListViewItem();
recs.Text = dr["emp_first_name"].ToString() + " " +
dr["emp_last_name"].ToString();
recs.SubItems.Add(dr["dept_name"].ToString());
recs.SubItems.Add(dr["emp_email"].ToString());
etc...
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
}
}
}
I see several things here:
You never open the connection:
You reference a number of fields in the reader that are not included in your statement's select clause.
You overwrite, rather than append to, the text property of your ListViewItem, so that only the last assigned property value will show.

Resources