I'm requested to work with a bit of code that uses an SqlDataAdapter, and I was wondering if this is the right approach.(I have looked at the documentation, but it's not totally clear in my mind)
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM MY_TABLE";
var Adapter = new SqlDataAdapter(cmd);
DataSet Result = new DataSet();
Adapter.Fill(Result);
Edit : think I found what was missing :
connectionString = help.Get_MyConnectionString();
Connection = new SqlConnection(connectionString);
Connection.Open();
Should work better with the connection open -.-"
Yes you need to open the connection. I would also wrap your SqlConnection and SqlDataAdapter in using blocks so that they are properly disposed.
using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
{
conn.Open();
using (var adapter = new SqlDataAdapter(
"SELECT * FROM MY_TABLE", conn))
{
var result = new DataSet();
adapter.Fill(result);
}
}
Related
I try to fill my dataset with multiple tables using stored procedure on SQLServer. Code is simple:
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(myDataSet);
}
}
}
But somehow Fill only creates (and fills) first table (not the others). It is not about procedure because it returns normal data. Am I missing something in the adapter?
I still don't know why Fill is not working. It worked before. There's walkaround (without need to specificate your datatables) but it envolves SqlDataReader
var execProcedureString = "EXEC dbo.SomeProcedure ..."
var myDataSet = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(execProcedureString, conn))
{
conn.Open();
using (var reader = new command.ExecuteReader())
{
while(!reader.IsClosed) //table.Load closes reader if it contains no more rows
{
var table = new DataTable();
myDataset.Tables.Add(table);
table.Load(reader)
}
}
}
}
I have problem with running this:
i captured picture from my win
OleDbConnection con = new OleDbConnection();
DataTable dt = new DataTable();
con.ConnectionString = "Provider=MSDAORA;Data Source=DATA;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT
DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE
DEPARTMENT_NAME=#depName)";
OleDbCommand command = new OleDbCommand(sqlcommand, con);
command.Parameters.AddWithValue("#groupName", textBox1.Text);
command.Parameters.AddWithValue("#depName", comboBox1.SelectedItem);
OleDbDataAdapter oda = new OleDbDataAdapter(command);
oda.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
Change the sqlcommand string as shown below,
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT "+
"DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE "+
"DEPARTMENT_NAME=#depName)";
This should solve the issue.
Observation: It is not a good practice to directly set the textBox1.Text value in parameter.
Trying to get MiniProfiler to profile loading a DataTable via a Stored Proc
// Use a DbDataAdapter to return data from a SP using a DataTable
var sqlConnection = new SqlConnection(#"server=.\SQLEXPRESS;database=TestDB;Trusted_Connection=True;");
DbConnection connection = new StackExchange.Profiling.Data.ProfiledDbConnection(sqlConnection, MiniProfiler.Current);
var table = new DataTable();
DbDataAdapter dataAdapter = new SqlDataAdapter("GetCountries", sqlConnection);
ProfiledDbDataAdapter prdataAdapter = new ProfiledDbDataAdapter(dataAdapter, null);
// null reference exception here - SelectCommand is null
prdataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
prdataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#countryID", 2));
prdataAdapter.Fill(table);
ViewBag.table = table;
Problem: Null reference exception on SelectCommand
Please ignore lack of usings / disposing
I can successfully profile using ProfiledDbCommand to a SP:
// call a SP from DbCommand
var sqlConnection2 = new SqlConnection(#"server=.\SQLEXPRESS;database=TestDB;Trusted_Connection=True;");
DbConnection connection2 = new StackExchange.Profiling.Data.ProfiledDbConnection(sqlConnection2, MiniProfiler.Current);
if (connection2 != null)
{
using (connection2)
{
try
{
// Create the command.
DbCommand command = new SqlCommand();
ProfiledDbCommand prcommand = new ProfiledDbCommand(command, connection2, null);
prcommand.CommandType = CommandType.StoredProcedure;
prcommand.CommandText = "dbo.GetCountries";
prcommand.Parameters.Add(new SqlParameter("#countryID", 3));
prcommand.Connection = connection2;
//command.CommandText = "SELECT Name FROM Countries";
//command.CommandType = CommandType.Text;
// Open the connection.
connection2.Open();
// Retrieve the data.
DbDataReader reader = prcommand.ExecuteReader();
while (reader.Read())
{
var text = reader["Name"];
result += text + ", ";
}
}
catch (Exception ex)
{
}
}
}
Edit1:
This works:
// 2) SqlConnection, SqlDataAdapter.. dataAdapter command - works
var sqlConnection = new SqlConnection(#"server=.\SQLEXPRESS;database=TestDB;Trusted_Connection=True;");
var table = new DataTable();
//var dataAdapter = new SqlDataAdapter("GetCountries", sqlConnection);
var dataAdapter = new SqlDataAdapter("select * from countries", sqlConnection);
//dataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
//dataAdapter.SelectCommand.Parameters.AddWithValue("#countryID", 2);
dataAdapter.Fill(table);
This doesn't DataTable.. but does with DataSet
var sqlConnection = new SqlConnection(#"server=.\SQLEXPRESS;database=TestDB;Trusted_Connection=True;");
DbConnection connection = new ProfiledDbConnection(sqlConnection, MiniProfiler.Current);
DbDataAdapter dataAdapter = new SqlDataAdapter("select * from countries", sqlConnection);
ProfiledDbDataAdapter prdataAdapter = new ProfiledDbDataAdapter(dataAdapter, null);
var table = new DataTable();
var dataset = new DataSet();
// Doesn't work
//prdataAdapter.Fill(table);
// Does work
prdataAdapter.Fill(dataset);
It turns out that though ProfiledDbDataAdapter inherited from DbDataAdapter, it did not override the default functionality of DbDataAdapter.Fill(DataTable), leading to the errors that you saw.
I fixed this in the MiniProfiler code. Fix is available in nuget, version 3.0.10-beta7 and higher.
I have tested this with your code from above and it works for me:
DbConnection connection =
new ProfiledDbConnection(sqlConnection, MiniProfiler.Current);
var sql = "select * from countries";
DbDataAdapter dataAdapter = new SqlDataAdapter(sql, sqlConnection);
ProfiledDbDataAdapter prdataAdapter = new ProfiledDbDataAdapter(dataAdapter);
var table = new DataTable();
dataAdapter.Fill(table); // this now works
Im getting error: net: unknown error 1
This is my code:
private void btnLogin_Click_1(object sender, EventArgs e)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 0;
cmd.CommandText = "hhrcv_logon_validation";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pv_emp_username", OracleDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("pv_emp_password", OracleDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add(new OracleParameter("pv_return_message", OracleDbType.VarChar));
cmd.Parameters["pv_return_message"].Direction = ParameterDirection.Output;
string valid;
conn.Open();
**cmd.ExecuteNonQuery();**
valid = cmd.Parameters["pv_return_message"].Value.ToString();
if (valid.ToString() == "")
{
frmHome main = new frmHome(lblEmp_id_no.Text);
main.Show();
this.Hide();
}
else
{
MessageBox.Show("" + valid, "Error");
}
conn.Close();
}
Unhandled exception on cmd.ExecuteNonQuery();
Everything was working fine till today. First time that I'm getting this.
Its not really descriptive. Can someone please assist.
Our DBAs implemented password expiry dates on our user accounts. The one we were using for the app was expired. Although I could still use the account to make the connection to DB and actually query data in the DB it didn't want to work from the app.
So issue is solved.
I am trying to call a oracle stored procedure in c# like this
OdbcDataAdapter da = new OdbcDataAdapter();
da.SelectCommand = new OdbcCommand();
da.SelectCommand.Connection = con;
da.SelectCommand.Connection.Open();
da.SelectCommand.CommandText = "KAMRAN.ATTN";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.SelectCommand.Connection.Close();
Label3.Text = "Attendance Posted Successfully";
But I am showing this error
ERROR [42000] [Oracle][ODBC][Ora]ORA-00900: invalid SQL statement
Please any One Can tell what exactly i am missing to call this procedure.plz help !
You could try to inverse the statements:
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
Also, maybe try to add:
da.SelectCommand.Parameters.Clear();
before
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
I think that you should also use a DataTable
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
Maybe that it should also be an Oracle Data Adapter:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand();
So you should have:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand();
da.SelectCommand.Connection = con;
da.SelectCommand.Connection.Open();
da.SelectCommand.Parameters.Clear();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
da.SelectCommand.Connection.Close();
I hope this helps in any way.