I have an openquery SQL script:
Select * from openquery([oak],'
SELECT LicenseKey, SUM(PaymentAmount)as Payments
FROM vw_ODBC_actv_Payments pt
WHERE MONTH(pt.EntryDate) = 2 and
YEAR(pt.EntryDate) = 2015
GROUP BY LicenseKey
')
When I run this from SSMS I can see that it returns expected n rows.
However when I'm firing this with the same connection properties to get the data in a DataSet for a C# console application:
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand pcmd= new SqlCommand();
DataSet ds= new DataSet();
OpenConnection();
pcmd.Connection = new SqlConnection("Data source=IP adress of the server;Initial Catalog=master; user ID=***; password=***");
cmd.CommandText = "Select * from openquery([oak],'" +
"SELECT LicenseKey, SUM(PaymentAmount)as Payments" +
"FROM vw_ODBC_actv_Payments pt " +
"WHERE MONTH(pt.EntryDate) = 2 and" +
"YEAR(pt.EntryDate) = 2015" +
"GROUP BY LicenseKey')";
try
{
da.SelectCommand = pcmd;
da.Fill(ds); //here comes the error
}
catch (Exception ex)
{
throw new Exception("DBUtils.ExecuteReader():" + ex.Message);
}
I'm getting an error like this:
The provider indicates that the user did not have the permission to
perform the operation. Now I need to do something with this issue
I'm just learning about openquery. Can anybody guide?
Firstly you're not opening the connection anywhere in your code hence the error. Second clean up your code with the using block. So assuming the query works as required you can do something like.
using(SqlConnection con = new SqlConnection("Connection String Here"))
{
string myQuery = "Your Query";
using(SqlCommand cmd = new SqlCommand(myQuery, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
}
}
}
Note: It would be a better if you stored the connectionString in your config file and read it in your code.
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
These are the tables in my project:
I am trying to update a DataGridView so that it displays the data of the user who is logged in.
I am getting the error: 'Must declare scalar variable '#CurrentUserID'... I think this is because I cannot convert the value to an int but if this is the case how do I fix the problem?
This is my code so far:
//Find ID of user who is logged in
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True");
SqlCommand command = new SqlCommand("select UserID from Users where Username = '"+loggedInLabel.Text+"' ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int currentUserID = reader.GetInt32(reader.GetOrdinal("UserID"));
command.Parameters.Add("#CurrentUserID", SqlDbType.Int);
command.Parameters["#CurrentUserID"].Value = currentUserID;
//update datagridview
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #CurrentUserID";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
dataGridView.DataSource = ds;
dataGridView.DataMember = "Records";
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Just in case anyone else was stuck with it.
I solved it by removed the code where I added the parameters and replacing it with :
dataadapter.SelectCommand.Parameters.AddWithValue("#CurrentUserID", currentUserID);
Thanks for the help!
You have many errors in your code, you're not disposing anything and re-using the command in a invalid way (while the reader is executing).
You're not using parameters. You're not re-using the SQL Connection. You're not adding parameters in the correct way.
This is how the code should look
try
{
DataSet records = new DataSet();
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True"))
{
int? userId = null;
using (SqlCommand command = new SqlCommand("select UserID from Users where Username = #Username", conn))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = loggedInLabel.Text;
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
if (reader.Read())
userId = reader.GetInt32(reader.GetOrdinal("UserID"));
conn.Close();
}
if (userId == null) // No row found
throw new ApplicationException("User not found");
using (SqlCommand command = new SqlCommand("select * from Records where UserID = #CurrentUserID", conn))
{
command.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = userID.Value;
// SqlDataAdapter opens and closes the connection itself.
using (SqlDataAdapter dataadapter = new SqlDataAdapter(command))
dataadapter.Fill(records , "Records");
}
}
//update datagridview
dataGridView.DataSource = records ;
dataGridView.DataMember = "Records";
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
You should also combine SQL Queries
select UserID from Users where Username = #Username and select * from Records where UserID = #CurrentUserID can be combined into this:
select Records.*
from Records
join Users
on Users.UserID = Records.UserID
where Users.Username = #Username
Then you only have to supply the Username and you'll get the records if everything is there.
I'm using the code below. When the SQL Server is off I get an error
the server was not found or was not accessible
when I'm in debug mode in VS2013 (as expected). If I launch the program outside of the IDE it just crashes.
How can I catch and handle the situation if the SQL Server can't be contacted?
using (SqlConnection con = new SqlConnection(connectionString))
{
CmdString = "SELECT * FROM Conversions WHERE Completed = 'False'";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Conversions");
sda.Fill(dt); // this is where the exception happens
}
This worked, thanks guys!
using (SqlConnection con = new SqlConnection(connectionString))
{
CmdString = "SELECT * FROM Conversions WHERE Completed = 'False'";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Conversions");
try
{
sda.Fill(dt);
}
catch (SqlException sqlexc)
{
MessageBox.Show("Error: " + sqlexc.Message);
Environment.Exit(0);
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
Environment.Exit(0);
}
}
I am new in C-Sharp, i am trying to access my Database from C-Sharp, i have written the following code, and i dont know what to write next to view data. I have searched this on net but didnt get much. Kindly tell me this in easy code.
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
Refer following code:
string strProvider = "#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
Hope its helpful.
Try this
try
{
Dataset myDataSet=new Dataset();
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );
connection .Open();
myDataAdapter.Fill(myDataSet,"TableName");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
connection .Close();
}
Remember for good coding practice ,always connection should be open in Try Block
and closed in Finally Block
This is my code:
This is in a different class named DBAccess
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = " SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN '" + dtpCeiling + "' AND '" + dtpFloor + "'";
SqlDataAdapter da = new SqlDataAdapter(newCmd);
DataSet dsIncome = new DataSet();
da.Fill(dsIncome, "Client");
conn.Close();
return dsIncome;
}
Below Coding is in the ProfitLos form class
public void btnClickFillGrid()
{
DataSet dsIncome = dba.getRecords(dtpFloor.Value.ToString(), dtpCeiling.Value.ToString()); //dba is an object of DBAccess class
dgvproIncome.DataSource = dsIncome.Tables["Client"].DefaultView;
}
btnClickFillGrid() will invoke at the button click event.
In the database - invdate datetime;(invDate is the variable name and its in the datetime format)
i edited my coding like this
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
using (SqlConnection conn = new SqlConnection("Data Source=KOSHITHA-PC;Initial Catalog=ITP;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
string sql = "SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN" + "#from AND #to";
command.CommandText = sql;
command.Parameters.AddWithValue("#from",dtpFloor);
command.Parameters.AddWithValue("#to", dtpCeiling);
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet dataSetClient = new DataSet();
da.Fill(dataSetClient, "Client");
return dataSetClient;
}
}
}
DataSet dataSetClient = dba.getRecords(dtpFloor.Value, dtpCeiling.Value);
dgvproIncome.DataSource = dataSetClient.Tables["Client"].DefaultView;
now i m getting an exception in "da.Fill(dataSetClient, "Client");" line saying
sqlException was unhandled
An expression of non-boolean type specified in a context where a condition is expected, near 'BETWEEN#from'.
i m not familiar with the parameter passing method to sql query,so couldnt find the problem that i m having
Look at this call:
dba.getRecords(dtpFloor.Value.ToString(), dtpCeiling.Value.ToString());
That's clearly passing in strings as the arguments. Now look at your method declaration:
public DataSet getRecords(DateTime dtpFloor,DateTime dtpCeiling)
Those parameters are of type DateTime, not string. So the first thing to fix is the call, to:
dba.getRecords(dtpFloor.Value, dtpCeiling.Value);
Now the next problem is that you're embedding the values in the SQL directly. Don't do that. Never do that. In some cases it can lead to SQL injection attacks, and in other cases it causes data conversion issues (as you've got here). Use parameterized SQL instead - oh, and use connection pooling rather than trying to use a single connection in multiple places:
public DataSet GetRecords(DateTime dtpFloor,DateTime dtpCeiling)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
string sql = "SELECT * FROM dbo.ClientInvoice WHERE invDate BETWEEN "
+ "#from AND #to";
command.CommandText = sql;
command.Parameters.AddWithValue("#from", dtpFloor");
command.Parameters.AddWithValue("#to", dtpCeiling");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
da.Fill(dataSet, "Client");
return dataSet;
}
}
}