C# database writing to table doesn't work - c#

I have a problem using Visual Studio 2010. I am using a service-based database (.mdf).
I have created a table manually in Visual Studio with some information. The code I have written can read from the table but when I insert new information it looks like the data is added to some other database.
I can read information from the correct table but when I add information to the table I can’t see the changes in Server Explorer in Visual Studio.
I don't know why to different databases are used! Does anybody know the problem?
Here is my code:
public class DataAccess
{
private SqlConnection sqlConnection;
private SqlCommand sqlCommand;
private SqlDataAdapter dataAdapterAnimal;
private DataSet dataset;
private string connectionString = DBAccessLayer.Properties.Settings.Default.AnimalDBConnectionString;
public DataSet LoadAnimalDataSet()
{
dataset = new DataSet();
using (sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
dataAdapterAnimal = new SqlDataAdapter("SELECT * FROM AnimalTable", sqlConnection);
dataAdapterAnimal.Fill(dataset, "AnimalTable");
sqlConnection.Close();
return dataset;
}
}
public void AddAnimal(int animalID, string name, double age, string category, string gender, string extraAnimalInfo)
{
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand("INSERT INTO AnimalTable VALUES(#AnimalID, #Name, #Age, #Category, #Gender, #ExtraAnimalInfo)", sqlConnection);
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("#AnimalID", animalID));
sqlCommand.Parameters.Add(new SqlParameter("#Name", name));
sqlCommand.Parameters.Add(new SqlParameter("#Age", age));
sqlCommand.Parameters.Add(new SqlParameter("#Category", category));
sqlCommand.Parameters.Add(new SqlParameter("#Gender", gender));
sqlCommand.Parameters.Add(new SqlParameter("#ExtraAnimalInfo", extraAnimalInfo));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
throw;
}
}

I haven't seen your connection string yet - but from your description, it seems it might be this problem here:
the whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...

Related

Cannot create new record to the database; no error message

I'm trying to add new record to trans_daily table, however, the code snippet below executed on button click doesn't work.
THE PROBLEMATIC CODE
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
string strcom = "INSERT INTO trans_daily (retail_id, cust_name, quantity, " +
"price, date, visibility, remarks_id) VALUES (#RetailID, #CustomerName, " +
"#Quantity, #Price, #Date, #Visibility, #RemarksID)";
SqlCommand cmd = new SqlCommand(strcom, connection);
cmd.Parameters.AddWithValue("#RetailID", ddRetailType.SelectedValue);
cmd.Parameters.AddWithValue("#CustomerName", tbCustomer.Text);
cmd.Parameters.AddWithValue("#Quantity", float.Parse(tbQuantity.Text));
cmd.Parameters.AddWithValue("#Price", float.Parse(tbPrice.Text));
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#Visibility", 1);
cmd.Parameters.AddWithValue("#RemarksID", 1);
cmd.ExecuteNonQuery();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
The following are the data types:
retail_id (int)
cust_name (varchar50)
quantity (float)
price (float)
date (datetime)
visibility (int)
remarks_id (int)
It's also worth to point out that no exception is being thrown.
What could have gone wrong?
THE WORKING CODE
In a separate function, I was able to pull out data from retail table on form load and placed the pulled out data to a dropdown list.
private void formAddTransaction_Load(object sender, EventArgs e)
{
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.MVGasConnectionString;
objConnect.Sql = "SELECT * FROM retail";
objConnect.connection_string = conString;
ds = objConnect.GetConnection;
MaxRows = ds.Tables[0].Rows.Count;
FillRetailTypes(conString);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
public void FillRetailTypes(string constring)
{
ddRetailType.DataSource = ds.Tables[0];
ddRetailType.ValueMember = "id";
ddRetailType.DisplayMember = "type";
}
Try this code and you may find your error:
try
{
using(SqlConnection connection = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand())
{
connection.Open();
string strcom = "INSERT INTO trans_daily ([retail_id], [cust_name], [quantity], " +
"[price], [date], [visibility], [remarks_id]) VALUES (#RetailID, #CustomerName, " +
"#Quantity, #Price, #Date, #Visibility, #RemarksID)";
cmd.CommandText = strcom;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#RetailID", SqlDbType.Int);
cmd.Parameter["#RetailID"].Value = ddRetailType.SelectedValue;
cmd.Parameters.AddWithValue("#CustomerName", SqlDbType.VarChar);
cmd.Parameter["#CustomerName"].Value = tbCustomer.Text;
cmd.Parameters.AddWithValue("#Quantity", SqlDbType.Float);
cmd.Parameter["#Quantity"].Value = float.Parse(tbQuantity.Text);
cmd.Parameters.AddWithValue("#Price", SqlDbType.Float);
cmd.Paramter["#Price"].Value = float.Parse(tbPrice.Text);
cmd.Parameters.AddWithValue("#Date", SqlDbType.DateTime);
cmd.Parameter["#Date"].Value = DateTime.Now;
cmd.Parameters.AddWithValue("#Visibility", SqlDbType.Int);
cmd.Parameter["#Visibility"].Value = 1;
cmd.Parameters.AddWithValue("#RemarksID", SqlDbType.Int);
cmd.Parameter["#RemarksID"].Value = 1;
int affectedRows = cmd.ExecuteNonQuery();
Console.WriteLine("You have inserted {0} rows", affectedRows);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
This code will...
... automatically open and close your database connection and command object
... log the amount of affected rows in the database to the console
... log exception messages to the console. You may add a breakpoint to this line if you want to see the whole exception (if one occures)
As explained in this blog, it seems like the problem is in the connection string.
Inside the project folder, 2 .mdf files were created: one is found at the root of the folder (let's call it mdf_1) and the other is inside the bin\Debug folder (let's call it mdf_2).
Now, taking a look inside the Visual Studio (VS) editor, there are 2 .mdf files shown: one under the Server Explorer, and another under the Solution Explorer. Not taking note of the location (from the properties section) of these .mdf files made me think these 2 .mdf files were the same. The thing is, the one under the Server Explorer is mdf_1 while mdf_2 is the one under the Solution Explorer.
VS has a behavior that copies mdf_1 and overwrites mdf_2 everytime the program is run (because by default, .mdf is set to Copy always mdf_1 to mdf_2). My connection string was pointing to the mdf_2 which explains why despite cmd.ExecuteNonQuery() command returns 1, my successfully inserted records are always erased because of the behavior VS has. And since it is mdf_1 that is under Server Explorer, I could not verify the changes in DB. Simply put, I was making changes in mdf_2 while trying to look for the changes in mdf_1.
So to avoid this, I modified my connection string by changing the relative path |DataDirectory| in the connection string to the absolute path of mdf_1 so that no matter how often VS overwrites mdf_2, the changes I make during runtime in mdf_1 aren't overwritten. This was, changes are also reflected in the Server Explorer (where I verify if changes were actually made).
tl;dr : I was updating the .mdf file under bin\Debug folder during runtime while physically looking for the updates in the .mdf file located in the root of the project.

Interacting with SQL Server database in Visual Studio 2015

I realise this question could be quite broad but ive been searching for the past 2 days with no luck.
I've created a project in Visual Studio 2015 and created a new data source in that project using a cloud database created with SQL Server Management Studio.
I'm now trying to code a login page in the project, which gets a username and password from 2 textboxes on the UI and executes an SQL query to check if the user exists in the database and if their password is right.
I'm familiar with Java code for database connections, such as the prepared statement and resultset functions.
Is there something equivalent for C#?
Thank you, reference to helpful articles or code samples will be greatly appreciated.
I think this can help you :-
http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program
here is probably the fastest but not the best way to check it.
string yourConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Users.accdb; Persist Security";
using (OleDbConnection conn = new OleDbConnection(yourConnectionString))
{
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("Select * from UsersTable where UName = #Username and Pass = #Password"))
{
cmd.Parameters.AddWithValue("#Username", txtUserName.Text);
cmd.Parameters.AddWithValue("#Password", txtPass.Text);
using (OleDbDataReader r = cmd.ExecuteReader())
{
if (r.HasRows)
{
Console.WriteLine("User exists")
}
else
{
Console.WriteLine("User does not exist")
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

using SQLite database for smart device VS 2008

I'm developing an application for my WindowsCE packect PC(.netCF35) to read some parameters and record them in my SQLite database in Visual Studio 2008. I knew that I need to add SQLite references to my application (I had a succeed experience for my windows 7 application). So I downloaded related files from http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and I just could add System.Data.SQLite.dll (I couldn't add SQLite.Interop.102.dll to my references). Now when I run my application, I can't add any data to my database and it seems cmdwrite.ExecuteNonQuery(); doesn't work correct. I need to say my table name and structure is correct(I'm sure). You can see my code as follow:
SQLiteConnection con = new SQLiteConnection("Data Source=AMI.sqlite;Version=3;");
public bool Insert(string Meter_ID, string type, string readout, string timestamp)
{
sqlwrite = "INSERT INTO meters (id,type,val,timestamp) VALUES(?,?,?,?)";
try
{
SQLiteCommand cmdwrite = new SQLiteCommand(sqlwrite, con);
cmdwrite.Parameters.AddWithValue("#id", Meter_ID);
cmdwrite.Parameters.AddWithValue("#type", type);
cmdwrite.Parameters.AddWithValue("#val", readout);
cmdwrite.Parameters.AddWithValue("#timestamp", timestamp);
con.Open();
dbstate = "3";
cmdwrite.ExecuteNonQuery();
dbstate = "4";
con.Close();
return true;
}
catch
{
con.Close();
return false;
}
}
Insert("123", "456", "789", "123");
Does anybody have any experience to work with SQLite database in WindowsCE?

Struggling to insert record into "SQL Server Compact 4.0 Database" from my C# WinForm Application. (I'm using VS 2010))

In my C# Winform Application I have written a code to insert record into the "SQL Server Compact 4.0 Database". Also I had debug code line-by-line everything is working fine (without any error) but after insert functionality when I checked my database I found that record is not inserted into the database, I'm strange why it is happening..!
But I think it is happening because, "when I tried to add database in my project I got this error" Following is my code to insert record into the database--
// Retrieve the connection string from the settings file.
string conString = Properties.Settings.Default.snda_dbConnectionString;
//string conString = "Data Source=|DataDirectory|\\db_snda.sdf";
try
{
conString = conString +";Password = test#1;";
// Open the connection using the connection string.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
// Read in all values in the table.
using (SqlCeCommand cmd = new SqlCeCommand("INSERT INTO tbl_user_master" + "(user_id, password, user_type, user_title, first_name, middle_name, last_name, gender, dob, mobile_no, email_id, plant_code, div_code, region_code, reporting_to, releaving_date, created_date)" + " VALUES(#user_id, #password, #user_type, #user_title, #first_name, #middle_name, #last_name, #gender, #dob, #mobile_no, #email_id, #plant_code, #div_code, #region_code, #reporting_to, #releaving_date, #created_date)", con))
{
cmd.Parameters.AddWithValue("#user_title", strTitle);
cmd.Parameters.AddWithValue("#first_name", strFirstName);
cmd.Parameters.AddWithValue("#middle_name", strMiddleName);
cmd.Parameters.AddWithValue("#last_name", strLastName);
cmd.Parameters.AddWithValue("#gender", strGender);
cmd.Parameters.AddWithValue("#user_type", strUserType);
cmd.Parameters.AddWithValue("#plant_code", strPlantCode);
cmd.Parameters.AddWithValue("#div_code", strDivCode);
cmd.Parameters.AddWithValue("#region_code", strRegionCode);
cmd.Parameters.AddWithValue("#reporting_to", strReportingTo);
cmd.Parameters.AddWithValue("#user_id", strUserName);
cmd.Parameters.AddWithValue("#password", Encrypt(strPassword)); //Encrypt(strPassword)
cmd.Parameters.AddWithValue("#email_id", strEmailId);
cmd.Parameters.AddWithValue("#mobile_no", strMobileNo);
cmd.Parameters.AddWithValue("#dob", strDOB);
cmd.Parameters.AddWithValue("#created_date", strCreatedDate);
cmd.Parameters.AddWithValue("#releaving_date", strReleavingDate);
cmd.ExecuteNonQuery();
}
con.Close();
XtraMessageBox.Show("User Created Successfully.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
ResetAfterSubmit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Thank you...!
It is hapening because you mix up databases - the one you check is not the one that is used during insert as likely when you start the debugging of the program a copys created in the output folder - and then discarded when you stop the program.
This is not exactly a rare problem and a good indication of someone not using a search function to find a solution.

The specified table does not exist. [ table_Name] error

Hi all I have an small application to add the expense of the day.
For this I am using SQL compact database (CE). While inserting the record into a table name Expenses I am getting error
The specified table does not exist. [Expenses]
Insertion code is
using (var con =new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Acadamy.sdf;
Persist Security Info=False"))
{
con.Open();
try
{
var Cmd = new SqlCeCommand();
String sqlAddNew = #"INSERT INTO Expenses (name, amount,receipt,details)
Values(#name,#amount,#receipt,#details)";
Cmd = new SqlCeCommand(sqlAddNew, con);
Cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtName.Text;
Cmd.Parameters.Add("#amount", SqlDbType.NVarChar).Value = txtAmount.Text;
Cmd.Parameters.AddWithValue("#receipt", SqlDbType.NVarChar).Value = txtRecept.Text;
Cmd.Parameters.AddWithValue("#details", SqlDbType.NVarChar).Value = txtDetails.Text;
Cmd.ExecuteNonQuery();
}
catch (Exception exception)
{
txtAmount.Text = exception.ToString();
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
}
I am not getting why this error occurring.
Acadamy.sdf structure is as below:
I am able to retrieve data from another table of the same database. What will be the problem?
Whenever I get an error about a table that does not exist I use the SQL Server Management Studio and check if the table really is missing or if I just have a typo in my query.
Unfortunately the current version of the Management Studio no longer supports SQL Server Compact Database and you will have to use the 2008 version. You can get it directly from Microsoft: SQL Server 2008 R2 Management Studio Express

Categories