I have a method which returns DataSet.
protected DataSet GetProgramList()
{
DataSet ds1 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(#"SELECT * FROM Program", cn))
da.Fill(ds1, "Program");
}
return ds1;
}
I want to use a specific column from the DataSet in other Method which is below:
protected DataSet GetStudentByProgramID(int programID)
{
DataSet ds2 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(#"SELECT LastName, FirstName FROM Student JOIN Program on Program.ProgramID = Student.ProgramID WHERE ProgramID ="+programID, cn))
da.Fill(ds2, "Student");
}
return ds2;
}
For example I want to use, the column ProgramID from Program Table in first method. I know I have to store the returned dataset in a variable but How?
Given that you will have ds1 accessible for GetStudentByProgramID method
Then you can use it this way
rotected DataSet GetStudentByProgramID(int programID)
{
DataColumn programId = ds1.Tables[0].Columns["ProgramId"];
//to read row you can iterate from ds1.Table[0].Rows
DataSet ds2 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC\\sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(#"SELECT LastName, FirstName FROM Student WHERE ProgramID ="+programID, cn))
da.Fill(ds2, "Student");
}
return ds2;
}
Why don't you write one query?
SELECT programID, LastName, FirstName
FROM Program JOIN Student ON Program.Id=Student.ProgramId
That way, you'll have each student with their programID.
Related
I'm passing a query and parameter from a WinForm to a database class. The
The code on the Form looks like this:
string selectedComp = "CPSI";
string catsQuery = "SELECT id, category, old_value, old_desc, new_value, new_desc, reference1, reference2 FROM masterfiles.xref WHERE company_name = '#company' ORDER BY category, old_value";
Db categoriesData = new Db();
dgvCategories.DataSource = categoriesData.GetData(catsQuery, selectedComp);
And in my database class my code to populate the datatable/set is this:
public DataTable GetData(string selectQuery, string selectedComp)
{
NpgsqlConnection conn = new NpgsqlConnection(connString);
DataSet ds = new DataSet();
NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn);
cmd.Parameters.Add(new NpgsqlParameter("#company", selectedComp));
//cmd.Parameters.AddWithValue("#company", selectedComp);
//cmd.Parameters.Add("#company", NpgsqlDbType.Text);
//cmd.Parameters["#company"].Value = selectedComp;
try
{
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
conn.Close();
da.Fill(ds);
return ds.Tables[0];
}
}
But putting a breakpoint at NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);, selecctQuery hasn't changed - the '#company' is still in the query.
What am I missing?
The root problem is that you're passing the query to the data adapter instead of the command. Change
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
to
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
I would also use using to dispose of all objects, and don't close the connection until the dataset is filled:
using(NpgsqlConnection conn = new NpgsqlConnection(connString))
using(NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new NpgsqlParameter("company", selectedComp));
conn.Open();
using(NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
}
conn.Close();
return ds.Tables[0];
}
I have created a table name glossary in a database named ChatBotDataBase in SQL Server. I want to read the data in a special column of the table.
To do so, I have written this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = #"Data Source=shirin;Initial Catalog=ChatBotDataBase;
Integrated Security=True";
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = sc;
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
But there is an error in last line.
The error is :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll.
And here is a print screen of the mentioned table:
Can anyone help please?
Looks like you are confusing the Datatable called table with your database table in your sql server. In your image you show us the glossary table in your sql server, not the DataTable called table.
You get this error because you create an empty DataTable called table with DataTable table = new DataTable() but you didn't even fill your table. That's why it doesn't have any rows by default.
SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter.
using(SqlConnection sc = new SqlConnection(conString))
using(SqlCommand cmd = sc.CreateCommand())
{
cmd.CommandText = "SELECT * FROM glossary";
...
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
sda.Fill(table);
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
}
Below code will help you
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
sda.Fill(table , "glossary");
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
You haven't executed the query or populated the table. It is empty. It has no columns and no rows. Hence the error.
Frankly, though, I strongly suggest using a typed class model, not any kind of DataTable. With tools like "dapper", this can be as simple as:
var list = conn.Query<Glossary>("SELECT * FROM glossary").ToList();
With
public class Glossary {
public int Id {get;set}
public string String1 {get;set} // horrible name!
....
public int NumberOfUse {get;set}
}
Dear kindly first fill your table with the data.
And you should use checks because if there is no data then you get a proper message.check is below..
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
else if(dt.Rows.Count > 0)
MessageBox.Show("Table is empty");
And other advice is that you should display data into DataGrid.... Displaying data from Database into a message box is not a good programming approach..
For displaying DataTable into DataGrid in C# is as simple as below.
SqlCommand cmd = new SqlCommand("select * from student",con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
dt.TableName = "students";
da.Fill(dt);
dataGridView1.DataSource =dt;
using System.Data.Odbc;
OdbcConnection con = new OdbcConnection("<connectionstring>");
OdbcCommand com = new OdbcCommand("select * from TableX",con);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds,"New");
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables["New"];
you can get the connection string from:
http://www.connectionstrings.com/
I have this access db that I have a ddl for the state name and a ddl for the year. I have a gridview that I'd like to pass the value of the state drop down list into where clause. Obviously if I could use sql with the named parameters I would but this is what I'm stuck with and not sure exactly how to format it correctly.
the drop down list is name ddlStates. In the parameters I've tried
mycommand.Parameters.Add("#ddlStates")
here is the data set
public DataSet GetData()
{
DataSet ds;
using (OleDbConnection myConnString = new OleDbConnection())
{
myConnString.ConnectionString = connString;
using (OleDbCommand myCommand = new OleDbCommand())
{
myCommand.CommandText = "select * from tblTest where location = ?";
myCommand.Parameters.Add();
myCommand.Connection = myConnString;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = myCommand;
ds = new DataSet();
da.Fill(ds, "Grades");
}
}
return ds;
}
}//ends get data dataset
1.you need to open your connection
2.you can add the parameter as follows
public DataSet GetData()
{
DataSet ds;
using (OleDbConnection conn = new OleDbConnection(connString))
{
string query= "select * from tblTest where location = ?";
using (OleDbCommand myCommand = new OleDbCommand(query, conn))
{
myCommand.Parameters.AddWithValue("#ddlStates", <your value>);
conn.Open();
using (OleDbDataAdapter da = new OleDbDataAdapter(myCommand, conn))
{
ds = new DataSet();
da.Fill(ds, "Grades");
return ds;
}
}
}
}
myCommand.Parameters.AddWithKey("location", this.ddlStates.SelectedValue);
That assumes that the data type of the location column is textual. If it's numeric or something else then convert the SelectedValue to the appropriate data type first.
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";
//create the database query
string query = "SELECT * FROM relation";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
// create the DataSet
DataSet ds = new DataSet();
// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
{
// create the database query
string query1 = "SELECT * FROM [time] Where classid= '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
DataSet ds1 = new DataSet();
OleDbDataAdapter adapter1;
adapter1 = new OleDbDataAdapter(query1, conn);
adapter1.Fill(ds1);
MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
}
the result that i get not true in message box that i want the id of all rows having the same classid but in message box that i use just to verification before o continue i see the id of time table without be consider where
Shouldn't this part be changed from...
string query1 = "SELECT * FROM [time] Where classid+ '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
to...
string query1 = "SELECT * FROM [time] Where classid = '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
You seem to be using a plus symbol (+) instead of equals (=).
Give this a shot:
public DataSet GetRelations()
{
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
{
var results = new DataSet();
adapter.Fill(results);
return results;
}
}
}
public DataSet GetTimeResults()
{
DataSet dsRelations = GetRelations();
var dsResults = new DataSet();
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
foreach (DataRow row in dsRelations.Tables[0].Rows)
{
using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
{
// not entirey sure what the value of row.ItemArray[2] is ?
command.Parameters.Add(row.ItemArray[2]);
using (var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dsResults);
}
}
}
}
return dsResults;
}
Just invoke it and use it as you see fit:
public void Test()
{
DataSet dsTimeResults = GetTimeResults();
// Do whatever you need with the results
}
I can't understand what I am doing wrong, I can't seem to SELECT with a prepared statement. However I can INSERT with a prepared statement.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
cmd.fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
Any advice on this would be greatly appreciated!
To fill a DataSet you will need a DataAdapter.
Try this:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.SelectCommand = cmd;
dAdap.Fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
You need to use SqlDataAdapter
DataAdapter represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source
Check the following syntax:
private static DataSet SelectRows(DataSet dataset,
string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}