I have some troubles with dataset in c#. I want to fill it with content from the database, but can't get it to work.
Here is my code:
from the main database layer containing the connection string
public static SqlCommand GetDbCommand(string sql)
{
if (dbconn.State.ToString().CompareTo("Open") != 0)
Open();
if (dbCmd == null)
{
dbCmd = new SqlCommand(sql, dbconn);
}
dbCmd.CommandText = sql;
return dbCmd;
}
This is the method that should fill the dataset from my DBMovie class
public static DataSet GetMovieSet()
{
DataSet movieSet = new DataSet();
string sql = "select * from Movie";
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(movieSet);
DBConnection.Close();
return movieSet;
}
How do I connect the dataAdapter together with the database connection?
Connect the adapter to the command like so:
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = dbCmd; //Add this
da.Fill(movieSet);
Related
I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.
I have a method on a form for getting a dataset, which i'm trying to call to populate a combobox but the table is not being found. What am I missing?
Here's the dataset method...
public partial class frmForm2 : Form
{
#region Variables
//Connection string
string conString = ("Data Source=L008##\\#####; Initial Catalog=FiT; Integrated Security=SSPI;");
//Data Variables
int maxRows;
int userID = frmForm1.user_ID;
#endregion
#region SQL Conn & Dataset
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
//Return the dataset
return dsAddWO;
}
#endregion
And here's where I'm trying to call the method...
public frmForm2()
{
InitializeComponent();
try
{
//Request dataset
DataSet dsAddWO = GetDataSet(conString);
DataRow dRow;
int incRow = 0;
dRow = dsAddWO.Tables[0].Rows[incRow];
comboBox1.Text = dRow.ItemArray.GetValue(1).ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Any help much appreciated!
You must access to table 0 after you fill the Dataset because when You create a new dataset, it has no tables.
e.g.
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Return the dataset
return dsAddWO;
}
Hope it helps
Bye
You try to access the table before the dataset has been filled. A new dataset will not contain any tables.
How can I adapt my code to any changes that are made remain persistent?
As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.
adb.Update(dt);
However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.
Code
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("#username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("#status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.
You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.
Or generate them with SqlCommandBuilder:
public static DataSet SelectSqlRows(string connectionString,
string queryString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);
//code to modify data in DataSet here
builder.GetUpdateCommand();
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);
return dataSet;
}
}
I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}
I try to write a winform application:
I dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
Above part of codes looks unsufficient.How can I best loading dataset?
public class LoadDataset
{
public DataSet GetAllData(string sp)
{
return LoadSQL(sp);
}
private DataSet LoadSQL(string sp)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(sp, con);
DataSet ds;
try
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
finally
{
con.Dispose();
cmd.Dispose();
}
}
}
Here is a simple function I converted from VB to C# (http://www.developerfusion.com/tools/convert/vb-to-csharp/). I use this extensively.
Simple wrapper function to help return a dataset from and SQL statement via an existing connection.
This should have performance improvements over re-connected via a connection string each time. Wraps any SQL errors in to a custom format.
public System.Data.DataSet GetDataSet(string sqlStatement, System.Data.SqlClient.SqlConnection connection)
{
System.Data.DataSet functionReturnValue = default(System.Data.DataSet);
if (connection == null) {
throw new ArgumentNullException("connection");
}
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet dset = new System.Data.DataSet();
try {
// Connect to the database
if (connection.State != ConnectionState.Open) {
connection.Open();
}
if (connection.State != ConnectionState.Open) {
throw new MyCustomException("Connection currently {0} when it should be open.", connection.State));
}
// Create a command connection
cmd = new System.Data.SqlClient.SqlCommand();
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStatement;
}
//.ExecuteReader() 'Forward only Dataset
// Create a data adapter to store the inforamtion
adp = new System.Data.SqlClient.SqlDataAdapter();
dset = new DataSet();
{
adp.SelectCommand = cmd;
adp.Fill(dset, "Results");
}
// Return the resulting dataset to the calling application
functionReturnValue = dset;
}
catch (System.Data.SqlClient.SqlException objSE) {
functionReturnValue = null;
// Let the calling function known they stuffed up and give them the SQL to help out.
throw new JDDataException(System.String.Format("SQL :- {0}.", sqlStatement), objSE);
}
finally {
if ((cmd != null)) cmd = null;
if ((adp != null)) adp = null;
if ((dset != null)) dset = null;
}
return functionReturnValue;
}
public string GetSqlConnection()
{
return System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
}
public DataSet getDataSet(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
conn.Dispose();
da.Dispose();
return ds;
}