Update SQL LocalDB schema in C# WinForms Application through setup - c#

I am creating a C# WinForms Application along with SQL LocalDB. I am new to SQL and I am following this tutorial (timestamp: 5.50) to add database in project. I have also added a setup project to install the application to other PCs. When I installed the project for the first time it worked perfectly well, but when I updated the database schema (added one more column) the changes are not reflecting, updated version of setup & assembly and installed the setup file again, the database schema changes are not reflecting in the application. It is giving the following error:
My code is something like this:
private void load_list()
{
string conn = Properties.Settings.Default.dbAgeConnectionString;
SqlConnection sqlConn = new SqlConnection(conn);
string sqltext = "SELECT Name, Age, DOB from Users";
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqltext,sqlConn);
adapter.Fill(table);
sqlConn.Close();
lstRecords.DisplayMember = "Name";
lstRecords.ValueMember = "Id";
lstRecords.DataSource = table;
gvrecords.DataSource = table;
}
Connection String:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbAge.mdf;Integrated Security=True
I tried adding the database files manually in Application folder of Setup but still no results.
I searched on the internet but did not find any database version control or upgrade method for SQL LocalDB. Is there any way I can achieve this?
Thanks in advance.

Related

how to create a setup or installer file and adding MYSQL reference using visual studio C# and MYSQL for deploy my project into another system?

I'm develop a new project for Medical Laboratory by using visual studio C# WinForms for user interaction and MYSQL for database. After my successful build its running successfully in my windows machine. But the problem is when I install my project on another windows machine, the front end of UI running well but the database throw an error to me. The error is Authentication to host 'localhost' for user 'root' using method 'caching_sha2_password' failed with message: Unknown database 'login'. I think the error was I need to add MYSQL reference in my project. but I'm absolutely don't know how to do it. I'm really sorry to all coz I'm noob in C# and my English.
and literally thanks to all.
public partial class registration : Form
{
string connectionstring = "server = localhost; user id = root; database = login; password =
qwerty;";
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "ALTER TABLE register ADD UNIQUE INDEX(rgstrid);";
cmd.CommandText = "INSERT IGNORE INTO register(username, password,confirm) VALUES(#username,#password,#confirm)";
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = rgstrusrnmtxtbx.Text;
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = rgstrpswdtxtbx.Text;
cmd.Parameters.Add("#confirm", MySqlDbType.VarChar).Value = rgstrcnfrmtxtbx.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(table);
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show("Your Account resgistred Successfully", "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Account saved Successfully","Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
You probably need to include a reference to a library to talk to MySql, like the MySql.Data package. Adding it as a nuget reference should ensure the required files are installed with the rest of the application files.
Your installer also needs to install some software. The database engine itself if you are running a local database, but also a .net connector for the ado.net driver.
At least this is how we do it. You might be able to avoid some components depending how you are accessing the database.
When installing the database you should specify the root password. For example by giving the rootpasswd=qwerty parameter to the MySQLInstallerConsole.exe program.
Your install script also needs to setup the database, i.e. either run sql files to create any tables and fill it with data, or copy the database files themselves, or run some program to create the tables.

Writing data from C# to a MDF database

I have a C# piece of code which listens for mouse-up events and then the data is to be written to a database. I have a .MDF database file I locally created in Visual Studio within the application. I am using the below code for this.
The thing is when I open the .MDF database file in SQL Server Management Studio after installing the application, I can't see any rows of data. I can see the columns I created but no data. The "Server" in server explorer in Visual Studio shows up to be my laptop number it seems:
private void MouseUpEvent(object sender, KeyEventArgs e)
{
MousePressed = e.KeyCode.ToString();
int Counting = MousePressed.Split('/').Length - 1;
long TimePressed = _MousePressed_Length;
String DateToday = SQLDate;
String TimeToday = SQLTime;
float TimeNow = SQLTimeExactmilliseconds;
var guid = Guid.NewGuid().ToString();
var guid2 = guid + TimeNow;
string sqlCon = #"Data Source=.\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (var db = new SqlConnection(sqlCon))
{
db.Open();
var command = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Date);", db);
command.Parameters.AddWithValue("#Date", DateToday);
var command2 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Time);", db);
command2.Parameters.AddWithValue("#Time", TimeToday);
var command3 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Mousepress);", db);
command3.Parameters.AddWithValue("#Mousepress", TimePressed);
var command5 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#TimeExact);", db);
command5.Parameters.AddWithValue("#TimeExact", TimeNow);
var command6 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Id);", db);
command6.Parameters.AddWithValue("#Id", guid2);
command.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
db.Close();
}
}
When I try to open the .MDF database file in Server Explorer, I get this message from Visual Studio :
Database 'C:\Program Files (x86)\muhammadADIbrahim#outlook.com\Setup_Attention_Assist\Database1.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\Users\muham\OneDrive\Desktop\Attention_Residue\BAAB UL WORK\NIZAM\CURRENT SOFTWARE\NizamSolutionBackup2.6\Nizam.Monitor\Database1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The code compiles and works properly so I am guessing this is something that is just to do with the connection to the database.
What should happen is that the .mdf data gets installed along with the .msi file when the user installs the application locally and the data is written to the database. For any user, I should be able to take the local .mdf file and open it in SQL Server Management Studio and view the results.
Thanks,
Ibrahim
The problem with the mdf database is that you need to install SQLSever.
The problem with mySql is similar. SQLLite didn't seem to work well for me either.
I have ended up creating a .txt file for this which for now seems to be working fine.

How to connect postgreSQL DB with ASP .NET MVC project

I have a problem with connection to database in my .NET ASP application. Maybe has something wrong with App.config or Web.config.
It was connected to MSSQL by default but I have tried connect it to PostgreSQL by npgsql nuget package and entity framework.
It don't even see Database Server for PostgreSQL when I want to create Migration in my project in Visual Studio ( Enable-Migrations; Add-Migration Initial; Update-database).
Here are github links of my code:
webconfig
App.config
I want to know how make it right and make it work proprely.
using System;
using Npgsql; // Npgsql .NET Data Provider for PostgreSQL
class Sample
{
static void Main(string[] args)
{
// Specify connection options and open an connection
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;" +
"Password=pwd;Database=postgres;");
conn.Open();
// Define a query
NpgsqlCommand cmd = new NpgsqlCommand("select city from cities", conn);
// Execute a query
NpgsqlDataReader dr = cmd.ExecuteReader();
// Read all rows and output the first column in each row
while (dr.Read())
Console.Write("{0}\n", dr[0]);
// Close connection
conn.Close();
}
}

How to use local database .sdf in c# wpf?

I am trying to make a database application. I added local database from
add > new item > local database.sdf
In Server Explorer, I created a table in the database. But I am having trouble connecting to it.
I want to show all the data in a DataGrid.
My code:
string ConnectionString = #"Data Source=""c:\users\asus\documents\visual studio 2012\Projects\WpfApplicationLocalDB\WpfApplicationLocalDB\LocalDB.sdf""";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
List<DataRow> lis = dt.AsEnumerable().ToList();
DataGridView.ItemsSource = lis;
But when I build it, Visual Studio finds conn.open(); error. A message says that
SqlException was unhandled by user
Please help...
Also, can anyone suggest a tutorial of how can I create a simple database application in C#? Please help.
If you're using a .sdf file, you're using Microsoft SQL Server Compact Edition (SQL Server CE).
When using SQL Server CE, you must use SqlCeConnection and SqlCeCommand classes - not SqlConnection and SqlCommand (those are for the "full", server-based versions of SQL Server)

Getting a DataSet from an SQL Express Server C#

How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database.
You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
EDIT:
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter.
I think you need to narrow down the question somewhat... All the data? You mean, all the data in every table in every database? Well, the only answer to that is, a lot of code.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
SqlConnection: Connect to the database
SqlCommand: Talk to the database
SqlDataReader: Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
CodeProject: Beginners guide to accessing SQL Server through C#
DevHood: Accessing SQL Server Data in C# with ADO.NET
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek.
This can be done by using dataAdapter class.

Categories

Resources