This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Related
I was trying to create shortest possible code to execute "non query" commands. Is it possible somehow to instruct to implicitly open the connection without using conn.Open()
public static int ExecuteNonSelect(string nonSelect)
{
string conString = #"Data Source=...";
int affected;
using (SqlConnection conn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(nonSelect, conn))
{
conn.Open();
affected = cmd.ExecuteNonQuery();
conn.Close();
}
}
return affected;
}
In case of the SqlDataAdapter() class this was not needed:
public static DataTable ExecuteSelect(string selectQuery)
{
string constring = #"Data Source=...";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlDataAdapter da = new SqlDataAdapter(selectQuery, conn))
{
da.Fill(dt); // calls ExecuteReader internally
}
}
return dt;
}
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
I'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
I wanted to populate data table with the value taken from the database. I want to use Select condition with the values taken from textbox.. I have written the following code in C#, please tell me whether it is a right approach. It is showing exception about connection string.. but I wanted to know whether my approach is correct or not.. please do comment.
public partial class searchsale : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string scriptname = TextBox1.Text;
string accnum = TextBox2.Text;
string sql = #"select scriptname,accnum,Quantity,price from transac where scriptname = #sn, accnum = #an and transactio = 'Sell'";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#an", accnum);
cmd.Parameters.AddWithValue("#sn", scriptname);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = GetDataTable(sql);
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
private DataTable GetDataTable (string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
}
return dt;
}
}
The error with your code is because you have not set the connection property of your command .
and for using data table the most simple way is using :
try
{
var connection = #"your connection string";
//your command
var command = "your command";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
//Get data
dataAdapter.Fill(dataTable);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
//Use sqlEx.Number to hanlde excception more specific
//for example if sqlEx.Number -1 => Could Not Connect to Server.
}
catch (Exception ex)
{
}
Problem is in your below code line for GetDataTable (string sql) method. You will have to use ConnectionString property. I would suggest you to read about ADO.NET more from MSDN.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
Should be
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
It should look like
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
your code looks right except the connection string. You have declared the connection string at the beginning as
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
But in your connection initialization it looks like you are getting it from App config file.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
So instead of having connection in your code put it in the app config file and remove the connection from your code
something like this
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>
Thank you,
Birhanu
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
}
}
how we can export or import data from or to to Datagridview from Excel or Access file??
I need to know the code for export and import..any one help please
try this:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(#"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}
Here is another tutorial
or just use google
I'll try to extend previous post with Access sample:
DataTable LoadSchemaFromAccess(string szFilePath)
{
System.Data.OleDb.OleDbCommand cmd;
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szFilePath));
cnn.Open();
System.Data.DataTable schemaTable = cnn.GetSchema("Tables");
cnn.Close();
return schemaTable;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
string LoadDataFromAccess(string szTableName )
{
string GetData = L"SELECT * FROM " + szTableName;
System.Data.OleDb.OleDbCommand cmd;
string szColumns = "";
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection
(string.Format(L"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szPath));
cnn.Open();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = GetData;
OleDbDataAdapter adt = new OleDbDataAdapter(cmd);
adt.SelectCommand = cmd;
adt.Fill(dt);
cnn.Close();
return dt;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
Hope this helped.