I'm trying to connect to a local database (service-based database created in Visual Studio 2013).
I use this C# code:
string connectionstring = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"|DataDirectory|\\InvDB.mdf\";Integrated Security=True";
public int testpripojeni()
{
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand();
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
}
This function should connect to the database and count rows in table HlavniTab. But I get error on line
int pocet = (int)prikaz.ExecuteScalar();
It says
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteScalar: Connection property has not been initialized.
What should I do to fix it?
your sqlcommand was not assigned a connection
try
prikaz.Connection = pripojeni;
Connection property in SqlCommand must have to be populated. You can set the connection property using Constructor and also directly set the value to Connection property.
Try -
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand(pripojeni);
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
or
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand();
prikaz.Connection = pripojeni;
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
Related
I have a combobox on a windows form that I fill with a list of names. At the moment I have the following code inside the Form class and it works fine
// This section opens a connection to the database, selects all the portfolio names that have an "in Use" value of 1, and then
// fills Combo Box 2 with the values.
SqlConnection myConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30");
myConnection.Open();
SqlCommand myCommand2 = new SqlCommand();
myCommand2.Connection = myConnection;
myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
SqlDataReader myReader2 = myCommand2.ExecuteReader();
while (myReader2.Read())
{
comboBox2.Items.Add(myReader2[0]);
}
myConnection.Close();
I would like to be able to extract this into a separate method, and put it into a separate class for general utility methods. However, I'm stuck on a really simple issue. When I put the code into a class, I need to be able to tell it which combox box I want to fill, and I can't figure out how to pass in that information. Sorry if the answer is obvious, but any help would be gratefully received.
Thanks!
Well, if you want to extract, then extract:
// Let's extract a class: it should provide us standard cursors,
// e.g. Protfolio Names
public static class MyData {
// Let's enumerate items returned
public static IEnumerable<string> PortfolioNames() {
// Wrap IDisposable into using
//TODO: move Connection String into a separated method/property
using (SqlConnection con = new SqlConnection(/*connection string here*/)) {
con.Open();
// Make sql readable
//DONE: when presenting something to user, sort it (order by) esp. strings
string sql =
#" select Portfolio_Name
from Dbo.Name
where In_use = 1
order by Portfolio_Name";
// Wrap IDisposable into using
using (SqlCommand q = new SqlCommand(sql, con)) {
// Wrap IDisposable into using
using (var reader = q.ExecuteReader()) {
while (reader.Read())
yield return Convert.ToString(reader[0]);
}
}
}
}
}
And then use
// Adding items in one after one manner is often a bad idea:
// it makes UI repaint each time you add an item and cause blinking.
// Let's fill the ComboBox in one go via AddRange
comboBox2.Items.AddRange(MyData.PortfolioNames().ToArray());
You can use a helper class names Portfolio for data access. The method GetNames does not require a ComboBox instance. This increases the chance that you can reuse the method in another context.
public static class Portfolio
{
public static IList<string> GetNames()
{
SqlConnection myConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30");
myConnection.Open();
SqlCommand myCommand2 = new SqlCommand();
myCommand2.Connection = myConnection;
myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
SqlDataReader myReader2 = myCommand2.ExecuteReader();
var portfolioNames = new List<string>();
while (myReader2.Read())
{
portfolioNames.Add(myReader2[0]);
}
myConnection.Close();
return portfolioNames;
}
}
Then in your Form you can do something like this:
var names = Portfolio.GetNames();
foreach (var name in names)
{
combobox2.Items.Add(name);
}
It is so simple:
public class MyUtility
{
public static void FillComboBox(System.Windows.Forms.ComboBox comboBox)
{
//comboBox.Items.Clear(); //enable this line if required
using (SqlConnection myConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30"))
{
myConnection.Open();
using (SqlCommand myCommand2 = new SqlCommand())
{
myCommand2.Connection = myConnection;
myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
using (SqlDataReader myReader2 = myCommand2.ExecuteReader())
{
while (myReader2.Read())
{
comboBox.Items.Add(myReader2[0]);
}
}
}
//myConnection.Close(); //not required inside using block
}
}
}
you may use other methods to get connection string (e.g. from config file).
The usage is so simple, no extra code required:
MyUtility.FillComboBox(comboBox2);
I created a sale table which Insert function does not work properly. It shows the error message like this "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed." If I removed Sql Close Statement on Line 14, it shows this error msg "There is already an open DataReader associated with this Command which must be closed first." My code below work like this. I checked available stocks from my Product table. If quantity order is greater than quantity from Product Table, show error message. Otherwise, proceed to inserting order information into Sale Table. Any help is appreciated.
private void btnOrder_Click(object sender, EventArgs e)
{
int iQuantityDB;
int iCustomerID = Convert.ToInt32(txtCustomerID.Text);
int iProductID = Convert.ToInt32(txtProductID.Text);
decimal dPrice = Convert.ToDecimal(txtPrice.Text);
int iQuantity = Convert.ToInt32(txtQuantity.Text);
decimal dSubtotal = Convert.ToDecimal(txtSubTotal.Text);
decimal dGST = Convert.ToDecimal(txtGST.Text);
decimal dTotal = Convert.ToDecimal(txtTotal.Text);
string strConnectionString = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB; MultipleActiveResultSets=True;";
using (var sqlconn = new SqlConnection(strConnectionString))
{
sqlconn.Open();
string querySelectQuantity = #"Select Quantity from dbo.JeanProduct WHERE ProductID = #iProductID";
using (var cmdOrder = new SqlCommand(querySelectQuantity, sqlconn))
{
using (var sdRead = cmdOrder.ExecuteReader())
{
sdRead.Read();
iQuantityDB = Convert.ToInt32(sdRead["Quantity"]);
}
}
if (iQuantityDB > iQuantity)
{
string InsertQuery = #"INSERT INTO Sale(CustomerID, ProductID, Price, Quantity, Subtotal, GST, Total)VALUES(#iCustomerID, #iProductID, #dPrice, #iQuantity, #dSubtotal, #dGST, #Total)";
using (var InsertCMD = new SqlCommand(InsertQuery, sqlconn))
{
InsertCMD.Connection = sqlconn;
InsertCMD.Parameters.AddWithValue("#iCustomerID", iCustomerID);
InsertCMD.Parameters.AddWithValue("#iProdcutID", iProductID);
InsertCMD.Parameters.AddWithValue("#dPrice", dPrice);
InsertCMD.Parameters.AddWithValue("#iQuantity", iQuantity);
InsertCMD.Parameters.AddWithValue("#dSubtotal", dSubtotal);
InsertCMD.Parameters.AddWithValue("#dGST", dGST);
InsertCMD.Parameters.AddWithValue("#dTotal", dTotal);
InsertCMD.ExecuteNonQuery();
LoadDataonTable();
}
}
else
{
MessageBox.Show("no more stock");
}
sqlconn.Close();
}
}
You should change your connection string to
string strConnectionString = #"Data Source = KK\SQLEXPRESS;
Integrated Security = SSPI;
Initial Catalog = JeanDB;
MultipleActiveResultSets=True";
And do not close the connection between the Reader.Read and the ExecuteNonQuery.
You need at least Sql Server 2005 for this to work.
The connection used by a SqlDataReader cannot be used for other operations unless you set the connection string with the MultipleActiveResultSets key. Of course you could open two connection objects (with the same connection string) and use one for the SqlDataReader and one to Execute your command.
Not really linked to your problem, but I suggest to use a parameterized query also for the SELECT part of your code.
Moreover, you should use the Using Statement around the disposable object to ensure the proper closing and disposing also in case of exceptions. Finally, the syntax used in the INSERT INTO is not correct. I think that this code could explain some of the points explained above.
string strConnectionString = #"......;MultipleActiveResultSets=True;";
using(SqlConnection sqlconn = new SqlConnection(strConnectionString))
{
sqlconn.Open();
string querySelectQuantity = #"Select Quantity from dbo.JeanProduct
WHERE ProductID = #id";
using(SqlCommand cmdOrder = new SqlCommand(querySelectQuantity, sqlconn))
{
cmdOrder.AddWithValue("#id", Convert.ToInt32(txtProductID.Text));
using(SqlDataReader sdRead = cmdOrder.ExecuteReader())
{
if(sdRead.Read())
{
.....
string InsertQuery = #"INSERT INTO Sale(SaleID, CustomerID, ProductID,
Price, Quantity, Subtotal, GST, Total)VALUES(#iCustomerID,
#iProductID, #dPrice, #iQuantity,
#dSubtotal, #dGST, #Total)";
using(SqlCommand InsertCMD = new SqlCommand(InsertQuery, sqlconn))
{
InsertCMD.Parameters.AddWithValue("#iCustomerID", iCustomerID);
....
InsertCMD.ExecuteNonQuery();
LoadDataonTable();
}
}
else
{
MessageBox.Show("no more stock");
}
}
}
}
You've closed your SqlConnection after the reader execution / read cycle (and in the other error, you've kept the reader open while trying to execute another command).
Either close the reader and leave the connection open for the insert, or open a new connection for the insert.
Better still, use using to handle the disposal of the resources for you, and scope the DB resources to be released as soon as you are done with them, e.g.:
using (var sqlconn = new SqlConnection(strConnectionString))
{
sqlconn.Open();
string querySelectQuantity = "Select Quantity ...";
using var (cmdOrder = new SqlCommand(querySelectQuantity, sqlconn))
{
int iQuantityDB;
using (var sdRead = cmdOrder.ExecuteReader())
{
sdRead.Read();
iQuantityDB = Convert.ToInt32(sdRead["Quantity"]);
} // Dispose reader
// sqlconn.Close(); <-- Don't close
} // cmdOrder disposed here
if (iQuantityDB > iQuantity)
{
string InsertQuery = "INSERT INTO ...";
using var (InsertCMD = new SqlCommand(InsertQuery, sqlconn))
{
// ...
} // InsertCmd disposed here
}
} // Sql Connection disposed here
This will overcome many bugs, such as the one you've got where you are conditionally closing the command + connection in an if branch.
hello am working on back up access database using C#, i have four groups which is access configuration , database selection, database backup and database restore.
so on data configuration i have data source textbox user id textbox and password textbox on database selection i have database combbox so that i can select one so i wrote this code
public partial class Form11 : Form
{
private OleDbConnection conn;
private OleDbCommand command;
private OleDbDataReader reader;
string ole = "";
string connectionString = "";
public Form11()
{
InitializeComponent();
}
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";
conn = new OleDbConnection(connectionString);
conn.Open();
ole = "EXEC sp_databases";
command = new OleDbCommand(ole, conn);
reader = command.ExecuteReader();
cmbDatabases.Items.Clear();
while (reader.Read())
{
cmbDatabases.Items.Add(reader[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
the problem is i keep seeing object reference not set to an instance of an object, here i use access database but on SQL i didn't have such problem, please help me out with this thing.
thank you.
Conn is an object and is not instantiated yet when you are using conn.ConnectionString property
just flip the order this 2 lines
try
{
conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";
In your code, you are using your connection before instantiating your connection object. You need this first:
conn = new OleDbConnection();
The error should have referenced a line in your code that you were getting this problem - often relatively easy to track back from there to see what is null.
public void moveBooks(int quantityOfMovedBooks, int booksID)
{
int finalQuantityOfBooks = totalBooksInDB(booksID) - quantityOfMovedBooks;
queryString = "update Books set bQuantity='" + finalQuantityOfBooks + "'where bID=" + booksID;
myComm = new OleDbCommand(queryString, myConn);
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
}
public int totalBooksInDB(int bID)
{
int booksQuantity;
queryString = "select bQuantity from Books where bID=" + bID;
myComm = new OleDbCommand(queryString, myConn);
myConn.Open();
booksQuantity = (int)myComm.ExecuteScalar();
myConn.Close();
return booksQuantity;
}
im beginner in MSAccess Database and C#, im maintaing a Table in which there are 3 fields one is BookID, second is BookName, third is BookQuantity.. scope is when books are moved to aisle books should be subtracted from main inventory.. im using this approach.. but i wonder is there any better or efficient way of doing this..
thanx in advance
A couple of changes.
First, never use string concatenation to build sql command text. This leads to sql injection attacks. A very serious security problem
Second, your code for getting the number of books could result in a null value returned by ExecuteScalar and thus you will get an error
Third. The connection should be opened when needed, used, and then closed and disposed. Your code will fail to close and dispose the connection if, for whatever reason, you get an exception.
The using statement prevent this issue taking care to close and dispose of the connection also in case of exceptions.
Fourth well this is more a logical problem. I think that you can't move more books than those stored in the inventory, so add a check just to be safe-
public void moveBooks(int quantityOfMovedBooks, int booksID)
{
int quantity = totalBooksInDB(booksID);
if(quantity > quantityOfMovedBooks)
{
int finalQuantityOfBooks = quantity - quantityOfMovedBooks;
queryString = "update Books set bQuantity=? where bID=?";
using ( OleDbConnection myConn = new OleDbConnection(GetConnectionString() )
using ( OleDbCommand myComm = new OleDbCommand(queryString, myConn))
{
myComm.Parameters.AddWithValue("#p1", finalQuantityOfBooks);
myComm.Parameters.AddWithValue("#p2", booksID);
myConn.Open();
myComm.ExecuteNonQuery();
}
}
else
MessageBox.Show("Invalid quantity to move");
}
public int totalBooksInDB(int bID)
{
int booksQuantity = 0;
queryString = "select bQuantity from Books where bID=?";
using ( OleDbConnection myConn = new OleDbConnection(GetConnectionString() )
using ( OleDbCommand myComm = new OleDbCommand(queryString, myConn))
{
myComm = new OleDbCommand(queryString, myConn);
myComm.Parameters.AddWithValue("#p1", bID);
myConn.Open();
object result = myComm.ExecuteScalar();
if(result != null)
booksQuantity = Convert.ToInt32(result);
}
return booksQuantity;
}
I don't know why give me this error in the code:
Unable to read database file
I get this error on line da.fill(dt)?
I'm trying to select from my database and display them in my DayPilotScheduler1.
private void loadResources()
{
DayPilotScheduler1.Resources.Clear();
string roomFilter = "0";
if (DayPilotScheduler1.ClientState["filter"] != null)
{
roomFilter = (string)DayPilotScheduler1.ClientState["filter"]["room"];
}
SQLiteConnection con = new SQLiteConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=Korisnik;Integrated Security=True");
SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT [id], [name], [beds], [bath] FROM [RoomDetails] WHERE beds = #beds or #beds = '0'", con);
da.SelectCommand.Parameters.AddWithValue("beds", roomFilter);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
string name = (string)r["name"];
string id = (string)r["id"];
string bath = (string)r["bath"];
int beds = Convert.ToInt32(r["beds"]);
string bedsFormatted = (beds == 1) ? "1 bed" : String.Format("{0} beds", beds);
Resource res = new Resource(name, id);
res.Columns.Add(new ResourceColumn(bedsFormatted));
res.Columns.Add(new ResourceColumn(bath));
DayPilotScheduler1.Resources.Add(res);
}
}
Based on your connection string you're connecting to a SQL Server Express database, not a SQLite database.
Use a SqlConnection instead of SQLiteConnection (along with the corresponding DataAdapter, etc.).
Whenever thisn type of error arises, then there is a possibility of having errors in the connectionstring, so trace your web.config file.
In your above code, you have mentioned Sqliteconnection which should be Sqlconnection, and make the corresponding changes in the code.