简体   繁体   中英

SQL Server connection in WPF

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid . Connection is successfully created but when I show it in grid,it show db error(Exception handling). This is what I am doing.Thanks in advance.

  try
  {
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = new SqlCommand(Get_Data);              
       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);
       MessageBox.Show("connected");
       //dataGrid1.ItemsSource = dt.DefaultView;           
  }
  catch
  {
       MessageBox.Show("db error");
  }

It shows connected when i comment the line sda.Fill(dt);

Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection .

try
{
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = thisConnection.CreateCommand();
       cmd.CommandText = Get_Data;

       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);

       dataGrid1.ItemsSource = dt.DefaultView;           
}
catch
{
       MessageBox.Show("db error");
}

You don't assign the command any connection. You open the connection then create a command, but don't link the two.

Try something like:

SqlConnection conn = new SqlConnection(@"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();

string sql= "SELECT * FROM emp";     

SqlCommand cmd = new SqlCommand(sql); 
cmd.Connection = conn;

SqlDataAdapter sda = new SqlDataAdapter(cmd);               
DataTable dt = new DataTable("emp");
sda.Fill(dt);

Assign Connection Object to SqlCommand Object.

using (SqlConnection connection = new SqlConnection(
           connectionString))
{
    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandTimeout = 15;
    command.CommandType = CommandType.Text;
    command.CommandText = queryString;

    connection.Open();
   //Perfom desired Action

}

Add thisConnection as 2nd parameter in

Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)


try {
    string connectionstring = "@"
    Server = (local) Database = Sample_dbTrusted_Connection = Yes;
    "";
    SqlConnection thisConnection = new SqlConnection(connectionstring);
    thisConnection.Open();

    string Get_Data = "SELECT * FROM emp";

    SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);`
    DataTable dt = new DataTable("emp");
    sda.Fill(dt);
    MessageBox.Show("connected");
    //dataGrid1.ItemsSource = dt.DefaultView;           
} catch {
    MessageBox.Show("db error");
}

I use this code with Oracle and hope it will help you.

First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;

And using the following code

try
{
  string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
  using (OracleConnection connection = new OracleConnection(MyConString))
  {
  connection.Open();
  sqldb1 = "select * from DEMO_CUSTOMERS;";
  using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
  {
    DataTable dt = new DataTable();
    OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
    da.Fill(dt);
    db1.ItemsSource = dt.DefaultView;
  }
  connection.Close();
}
catch (Exception ex)
{
  MessageBox.Show(ex.ToString());
}

XAML code:

<DockPanel>
    <DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1"  AutoGenerateColumns="True" >
    </DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
        bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
        if (networkUp)
        {
            try
            {
                    SqlConnection connection = new SqlConnection("ConnectionString");
                    SqlCommand command = new SqlCommand(cmd);
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        sda.SelectCommand = command;
                        command.Connection = connection;
                        connection.Open();
                        sda.Fill(dt);
                        connection.Close();
                        if (dt != null && dt.Columns.Count > 0)
                            return dt;
                        else
                            return null;
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
        else
        {
            Console.WriteLine("Network is disconnect");
            return null;
        }
    return null;
}  

or :

  public void ExecuteNonQuery(string cmd)
        {
            bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
            if (networkUp)
            {
                try
                {
                  SqlConnection connection = new SqlConnection("ConnectionString");
                  SqlCommand command = new SqlCommand(cmd);
                  command.Connection = connection;
                  connection.Open();
                  command.ExecuteNonQuery();
                  connection.Close();
                }
                catch (Exception ex)
                {
                   Console.WriteLine(ex.Message);
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM