I am trying to create a WPF application for a client and a SQL server is required. I am currently using Visual Studio to develop everything, but I have never used SQL servers outside of web application before. I add a new SQL database to my WPF project by adding a "Service-based Database", and everything works fine. Until I transfer the project over to a different computer where it crashes and gives me the error "System.Data.SqlClient.SqlException: Database not found". Is there something that I'm missing about setting up a database inside my VS project? Why does it only work on my development PC and not any other that I transfer it to?
The code that it crashes on:
string cn_string = Properties.Settings.Default.connection_String;
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\_data\db_local.mdf;Integrated Security=True
string cmdString = "SELECT * FROM tbl_Clients";
using (SqlConnection con = new SqlConnection(cn_string))
{
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("tbl_Clients");
sda.Fill(dt);
MyDataGrid.ItemsSource = dt.DefaultView;
}
Sorry for my easy questions, I am currently learning programming in high-school. Thanks for all your help.
Using a service-based database requires you to set up a SQL Server service on the machine where you intend to run the WPF client application.
If you want an embedded database that you can xcopy deploy with your application, you should take a look at SQLite. It is, unlike the service-based database that you create in Visual Studio, completely self-contained and doesn't require you to install any service.
Related
Hello, I'm currently working on a project which contains a part in which you have to simply import data from database in different ways. My database is hosted on a local MySql server under localhost.
I want to know the most flexible and easy way to execute queries on my MySql database (of course in C# code). I've tried using string interpolation ($"" syntax) for modifying text of the query but I think it is not the best way to do this.
(its getting very complicated when you want to apply some more complex query)
cmd = new MySqlCommand("SELECT * FROM admin WHERE admin_username=#val1 AND admin_password=#val2", MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", "admin");
cmd.Parameters.AddWithValue("#val2", "pass");
cmd.Prepare();
MySqlDataReader res = cmd.ExecuteReader();
I have a problem I need to solve, but not know how exactly. I have a WinForms application (C#) which connects to an online MySQL server - no problem there. In this application I have an option to make database backups (basically I dump this database to a local file on a computer).
I would like to locally "open" this backup on client's computer (to check some old data) - I don't want to make database restore on my server, because database must still be in use for other users. I want to make clean install of MySQL on a local computer and connect to it trough localhost (like I do for testing ), but I do not have physical access to that computer. I can send MySQL installer to my client, but how to go about automatically creating user with password and database from my dump file?
I know how to create a new database if it doesn't exist, but how to do it if it's clean install of MySQL server - no user and password yet.
string connStr = "server=localhost;user=root;port=3306;password=????;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd.ExecuteNonQuery();
}
Any help and direction is appreciated.
Regards!
I don't know whether I understand your problem. However,if you install a new Mysql,you can use root user through no database.
Anyway, one thing you need to know,Connect database must has user and password for mysql or sqlserver.
You may need to be more concise description of your problem.
I'm recently new at C# and follow a tutorial on connection to the database, the connection for viewing or SELECT command was ok, I made some revision based on the threads of forums to make my code better, but when I was in INSERT for my SQL Server, I have some problems. I was able to insert the data but when I re-run the program the data that I just inserted earlier was not in the database.
Here is my code on insert
string commandText = "INSERT INTO loginInfo (name, pass, role) VALUES(#name, #pass, #role)";
using (connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#pass", textBox2.Text);
command.Parameters.AddWithValue("#role", textBox3.Text);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally
{
command.Connection.Close();
}
}
I'm trying to create a simple CRUD but not save the data... please help
If you're using the AttachDbFileName= clause in your connection string, you might have fallen victim to a well-known issue : you might just be looking at the wrong database (file) when checking your data.
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 connection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The long-term viable 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. YourDatabase)
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=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Good day,
My goal is to create a msi for a windows service and during installation various sql scripts must run.
What I want to do is create a msi that, when the user runs it, it installs the service on the pc and runs 3 .sql scripts, one for creating the database, one for population, and one to add a stored procedure.
I am able to add create a setup project for the service using the msdn overview
My problem is that I have no idea how to run a sql script during the install (and how to specify the sql connection)
Is there any way to do this in visual studio, or will I need to resort to batch files/purchasing InstallShield?
Any help is appreciated,
Regards
Jeff
EDIT: I am using visual studio 2010 Professional and SQLServer 2012
You can run the SQL script during the installation exactly the same way you'd do it in any other C# application.
In the MSDN overview you've mentioned in the question, there is reference to writing your own code during the installation, so I'll assume you already know how to do that.
There are many ways to do this. Here's just one example out of many, quoted from here:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = #tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;UserId=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
For my database I create a new query and wrote
select * from dbname
using SQL Server Management Studio Express 2005. Saved it by name SQLQuery1.sql on the desktop.
Now I would like to call this query from C# code when an ASP.NET button is clicked and display the results in a gridview.
How do I call the query? Can I tell Visual Studio 2008 to please execute the query stored in 'sqlquery1.sql' ?
Where do I store the results so that I can bind them the display controls like a gridview, or traverse the data?
This is a website in C#, ASP.NET, Visual Studio 2008, and database is on the same computer using SQL Server 2005 Express
You cannot just execute a SQL script you stored on your computer's desktop from an ASP.NET website.
You can either:
turn your query into a stored procedure in SQL Server, something like:
CREATE PROCEDURE dbo.proc_MyQuery
AS
SELECT (list of columns)
FROM dbo.MyTable
WHERE (condition)
When you do this, you can create a SqlCommand in your C# code and call that stored procedure and retrieve the results back.
or:
you can execute the query directly from your C# code by creating a SqlConnection and a SqlCommand object and running that SQL statement.
These are both absolutely basic ADO.NET features - you should find tons of learning resources online for this.
For instance:
ADO.NET 101 - Data Access with ADO.NET
ADO.NET 101: SQL Connection
ADO.NET 101: SqlCommand / Your guide to using this ADO.NET object to execute SQL Server commands
Using ADO.NET for beginners
ADO.NET for Beginners - Part 1
Which ever way you go, you basically need to have a SqlConnection to your database, and then a SqlCommand to execute the query. If you want to store the data so you can both bind it to a Gridview as well as navigate it in code, you probably want to store it in a DataTable. So your code would look something like this:
DataTable resultTable = new DataTable();
using(SqlConnection con = new SqlConnection("your connection string here"))
{
string sqlStmt = "SELECT (columns) FROM dbo.YourTable WHERE (condition)";
using(SqlCommand cmd = new SqlCommand(sqlStmt, con))
{
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(resultTable);
}
}
and then to bind to the gridview, you'd use something like:
myGridView.DataSource = resultTable;
myGridView.DataBind();
and to navigate the DataTable, you can step through its .Rows() collection of data rows.
In your server side event handler you will need to open the file from the desktop, read in the SQL, and then use the SQL to databind the grid.
This would depend on the identity that the website code runs under having read access to the desktop. By default it won't so you would need to give that identity (NETWORK_SERVICE?) permission. This could open up horrible security holes.
You would be better off moving the SQL somewhere more accessible, like web.config, or a file in the website directory.