I'm working on a small project that's unrelated to this, it needs a database to be integrated into it, so I looked into SQLite and tried to teach myself the basics.
My code works fine but I realised if I was to deploy this on another machine it wouldn't be able to connect to the database because it wouldn't have the file as I've hard coded it in (it's running of my C:\ drive currently which will be an issue for users who haven't got it there obviously).
I was wondering if it was possible to update to connection string for the user at runtime? Even say, when the user installs it, it installs a copy of the database and changes its path to that?
Here's my code:
using System;
using System.Windows.Forms;
using System.Data.SQLite;
namespace sqltest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string cs = #"Data Source=c:\student.db;Version=3;FailIfMissing=False";
string stm = "SELECT Name FROM Customer";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(stm, con);
using SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show($"{rdr.GetString(0)}");
}
}
}
}
Thanks for any help!
you can get datasource from config file, e.g. appsetting.json
The connection string that you pass to new SQLiteConnection(...); is actually being passed at runtime already.
Sounds like the simplest solution is to create the database if it doesn't already exists with a predetermined path. This will ensure that when your script runs on a machine that doesn't have a DB, the DB will be created at runtime.
Here's a relevant post: Programmatically create sqlite db if it doesn't exist?
Related
Recently we have had an issue with our ERP retrieving some information from our database tables. While this is being fixed I have come up with some work arounds to temporarily, however, they only work because my user has access to the SQL database and can run queries on the database. I would like to distribute an executable program throughout the company (we are relatively small, so I am not worried about bottle-necking my computer) that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. This way we don't need to make any changes to users SQL permissions.
How could I possibly do this?
Edit - Additional Info
User A - has permission to query the database on our servers from
their workstation
User B - does not have permission to query the db
User B needs to gather information from a specific db query, yet they don't have access to the db. All that User B needs, is to be returned a string with information from that query.
So not necessarily looking for the remote execution of a program per se, because then how would they get that return value?
I would do it with an application that does something like this.
using MySql.Data.MySqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection conn = null;
try
{
conn = new MySqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
MySqlCommand selCmd = new MySqlCommand("SELECT ...", conn);
MySqlDataAdapter da = new MySqlDataAdapter(selCmd);
....
This uses MySql, but the exact equivalent can be done with any DB provider. The part of the connection string that says Integrated Security=False tells the system not to use the current user's window credentials but rather what is being provided in the connection string.
The same thing but using Sql Server, I think, would be like this (it's been a while since I use sql server...
using System.Data.SqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
SqlCommand selCmd = new SqlCommand("SELECT ...", conn);
SqlDataAdapter da = new SqlDataAdapter(selCmd);
....
I assume based on the quote below - you are creating a program that you will send to user B to use to run the query and return a string.
"that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. "
If this is the case - User B doesnt need any data base permissions. You will put your [user A]'s username and password in the connection string of the program you create. So when User B runs this program you gave him, it will use User As permissions to run and return data.
like this:
<add name="myconnection" connectionString="data source=yoursqlserver;initial catalog=yourdataabase;persist security info=True;user id=UserA;password=userAspassword" providerName="System.Data.SqlClient" />
How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;
I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.
I am getting the Errors
"Unable to copy file "j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\MyApp01.mdf" to "bin\Debug\MyApp01.mdf".
The process cannot access the file 'bin\Debug\MyApp01.mdf' because it
is being used by another process."
and
"Unable to delete file "j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\bin\Debug\MyApp01.mdf". The process
cannot access the file 'j:\users\gary\documents\visual studio
2010\Projects\MyApp01\MyApp01\bin\Debug\MyApp01.mdf' because it is
being used by another process."
I have been working on getting this problem fixed for almost a week now, but still cannot fathom out what is wrong.
Today I have created a new Project called MyApp01 & connected a new 2 Column Database of the same name, and I edited the Properties to change the "Copy to Output Directory" status from "Copy Always" to "Copy if Newer". My understanding of this is that the database that is stored in the MyApp01 Folder creates a test version of it in the MyApp01\bin\Debug\ folder the first time it is accessed and then is only overwritten if the Database layout is changed. Is that correct ? If so, why am I getting these errors that seem to insinuate that the system is trying to replace the \bin\Debug\ version of the database ?
I ran the App for the first time & it seemed to work just fine, my database was updated with three records, these displayed in Form2 and I Quit out of it successfully. However, back in VS2010 I used the Server Explorer to Show Table Data and this shows the Database as empty, so I believe that insinuates it is looking at the version in the MyApp01 folder & not the version in the MyApp01\bin\Debug\ folder. Therefore I ran the program again and this is where I get these errors.
So, again, is my understanding of the way the database is copied and maintained correct, and if so (or if not !!) why am I getting these errors telling me that the system is trying to replace the \bin\Debug\ version of the database ?
This is my code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MyApp01
{
public partial class Form1 : Form
{
int myCount;
string myDBlocation = #"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\MyApp01.mdf;Integrated Security=True;User Instance=False";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myCount++;
//Insert Record Into SQL File
myDB_Insert();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
private void button3_Click(object sender, EventArgs e)
{
//Quit
myDB_Close();
this.Close();
}
void myDB_Insert()
{
using (SqlConnection myDB = new SqlConnection(myDBlocation))
using (SqlCommand mySqlCmd = myDB.CreateCommand())
{
mySqlCmd.CommandText = "INSERT INTO MyAppTbl(MyData) VALUES(#MyValue)";
mySqlCmd.Parameters.AddWithValue("#MyValue", myCount);
myDB.Open();
MessageBox.Show("State = " + myDB.State);
mySqlCmd.ExecuteNonQuery();
myDB.Close();
MessageBox.Show("State = " + myDB.State);
}
return;
}
void myDB_Close()
{
using (SqlConnection myDB = new SqlConnection(myDBlocation))
using (SqlCommand mySqlCmd = new SqlCommand())
{
myDB.Close();
}
return;
}
}
}
I have resolved this now by using a New Database that I created in MS SQL Server Management Studio and I added it to the VS2010 C# Project as an Existing Item, rather than a New Item.
I hope this helps anybody that runs into the same frustrating problems that I did !!!
I have a local project where I am trying to input data from an ASP:textbox to a database.
On building I get the following...
"Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance. The connection will be closed."
I'm a little puzzled here, I have checked the database and it is active with the credentials i am trying to connect with.
Here is the code behind
C#
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection sqlcon = new SqlConnection(#"user id=*myuserid*;"+"password=*mypassword*;"+"Data Source=mssql.dev-works.co.uk;User Instance=True;"+"Database=devworks_osqar"+"Trusted_Connection=true;");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Create_Click(object sender, EventArgs e)
{
DataBinder ds = new DataBinder();
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
}
Any help would be much appreciated.
Edited code behind (read commment below)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string myConnectionString;
private SqlConnection myConn;
public new_questionnaire()
{
myConn = new SqlConnection();
myConnectionString += "Data Source=mssql.database.co.uk; Initial Catalog=devworks_osqar;User ID=myusername;Password=mypassword";
}
protected void Create_Click(object sender, EventArgs e)
{
//DataBinder ds = new DataBinder();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
insert(sqlcmd);
}
private void insert(SqlCommand myCommand)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
}
Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."
Content from link pasted and altered below in case reference site is removed in the future:
Step 1.
Enabling User Instances on your SQL Server installation
First we are gonna make sure we have enabled User Instances for SQL Server installation.
Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
Run this query and then restart the SQL Server.
Step 2.
Deleting old files
Now we need to delete any old User Instances.
Go to your C drive and find and completely DELETE this path (and all files inside):
C:\Documents and Settings\ YOUR_USERNAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
(Dont forget to replace the bold text in the path with your current username (if you are not sure just go to C:\Documents and Settings\ path to figure it out).
After deleting this dir you can go to Visual Studio, create ASP.NET WebSite and click on your App_Data folder and choose Add New Item and then choose SQL Server Database and it should work!!!