OK, I've been working on this since late last night and early this morning. I am trying to insert some data into a SQL Server CE database. I am at the end of my rope.
Here is the code I am trying to implement:
public static void InsertData(string sqlStatement)
{
try
{
//string strConn = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
//string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6); // remove file:\\
//string connectionString = #"Data Source=Database1.sdf";
//string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
//string connectionString = string.Format("Data Source={0}; Persist Security Info=False;", Path.Combine(Application.StartupPath, "Database1.sdf"));
//THIS ONE ACTUALLY WORKS!!!!!!!!!!!! :
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
string connectionString = Properties.Settings.Default.Database1ConnectionString;
SqlCeConnection sqlceCon = new SqlCeConnection(connectionString);
sqlceCon.Open();
SqlCeCommand sqlCeCom = new SqlCeCommand(sqlStatement, sqlceCon);
sqlCeCom.ExecuteNonQuery();
sqlCeCom.Dispose();
sqlceCon.Close();
}
catch (Exception e)
{
}
}
You can see all of the commented connection strings to see what I have tried. The strange thing is that I can simply use the following connection string in another method (a SELECT statement, not an INSERT INTO statement) that gets a single value from the data and it works fine.
string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
I have tested the query directly and like the comment says, the static path does work so that tells me my query is good. But of course I need something relative for publishing and multi-developer development.
Most of the connection strings I have tried allow the try block to complete with no errors, but the data doesn't get inserted.
Any suggestions?
I searched my heart out before posting this question, but Simon is right about similarity. However, we're going to have a better answer here. Corak is correct. I set property to not copy, deleted copy in bin\debug folder and app wouldn't run in debug mode because it couldn't find db even though paths all point to other file location. App is looking for copy in bin\debug. Ultimately, it was working all along. I recommend someone to make a connection to the copy in bin\debug so they can test values in the Server Explorer. Thanks for your help Corak and everyone else.
/*If your solution is web application, make sure Database1.sdf location path is under the
* App_Data folder
* Web.Config <add name="LocalDB" connectionString="Data Source=|DataDirectory|\Database1.sdf"/>
*/
protected string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDB"].ToString();
}
}
/*
* or you can use try absolute path as connectionstring
* modify your directory path as PhysicalApplicationPath result
*/
public string BaseDirConnString
{
get
{
if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
{
throw new ApplicationException("...");
}
return #"Data Source=" + HttpContext.Current.Request.PhysicalApplicationPath + "VIN Decoder\\Database1.sdf";
}
}
protected SqlCeConnection SqlCeConnection
{
get
{
var connection = new SqlCeConnection(BaseDirConnString);
connection.Open();
return connection;
}
}
Related
I've run into a problem while making a project for school, we are supposed to import data from a .txt file to our C# database. I thought I had it figured out but my "insert" lines weren't inserting data to my tables. So, in the end, I tried to insert only 1 line with all values written in, and it still won't insert the data into the database.
I tried the "New query" option by right clicking on my table and copy-pasted the insert line from my code, and that worked just fine, so I don't know why the line in the code isn't working.
class Program
{
static void Main(string[] args)
{
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
string q;
dataConnection.Open();
q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
SqlCommand dataCommand = new SqlCommand(q, dataConnection);
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
dataConnection.Close();
}
catch { Console.WriteLine("Fail"); }
}
}
I tried pasting the executenonquery line in a try block, and it DOES write "Success" on my screen, but the insert line does NOT execute.
Check the return value of dataCommand.ExecuteNonQuery(); (integer Value) if it return -1 something went wrong (for example a transaction rollback). If 0 no rows were affected.
int return_value = dataCommand.ExecuteNonQuery();
if(return_value > 0)
//goood :)
else
//something wrong :(
EDIT:
Btw is better dispose the commands after using them like below:
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
dataConnection.Open();
string q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
using(SqlCommand dataCommand = new SqlCommand(q, dataConnection))
{
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
}
catch { Console.WriteLine("Fail"); }
}
dataConnection.Close();
EDIT2: Considering questions in the comments.
What are you saying writing |DataDirectory| is "search in the application path for that dasabase", if you're debugging your application it means that it search the dabase in the output debug folder... If you wont that you should target a database out of your appliation directory with a relative/absolute path (look AppDomain.SetData method) or copy your database in your application directory... is hard answer you without knowing your goal :)
To be more specific, before initialize your SqlConnection call the following code:
AppDomain.SetData("DataDirectory", "C:\\TEST\\");
To set your |DataDirectory| pointing at your database path.
I try to open a connection with a database from curent directory, and I searched on google and I found that I need to use " System.IO.Directory.GetCurrentDirectory() ". and I recive this error
Database 'D:\Work\C#\DatabaseLoginPassProj\DatabaseLoginPassProj\Database1.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:\Users\Mihai\AppData\Local\Temporary Projects\BazaDeDataIndependenta\bin\Debug\Database1.mdf' as database 'Database1.mdf'.
this is my code
private void InregistrareBTN_Click(object sender, EventArgs e)
{
string connstring = #" server=.\sqlexpress;
Database = Database1.mdf;
trusted_connection = true;
AttachDBFileName = " + System.IO.Directory.GetCurrentDirectory() +
#"\Database1.mdf;";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
}
Thanks.
Ps: I don't want to specify the full path of the DB because I need to make the program working on every pc.
I am using a method(GetConnectionString()) in a class(Utility.cs) as part of another method(fillDT()) in another class(Function.cs).
internal class Utility
{
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Assignment_new.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
class Functions
{
public static DataTable fillDT(string sqlstatement) //Fills the datatable with data from sqlstatement
{
string connstr = Assignment_new.Utility.GetConnectionString();
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlstatement, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Whenever I call Functions.fillDT(#"sql statement"), the error pops out saying connection string is not initialized.
Make sure you use proper config files to save your connection string. I see you are tagging this question as WinForms, so your connection string should be inside App.Config file not in Web.Config. If this a web application then you should do the opposite, keep it in Web.Config file at the top most directory.
Also, if this is a desktop application and you are using App.Config file to save your settings, make sure that file is copied to your output directory, where the executable stays (usually the same name as the executable. i.e <EXNAme>.exe.config). Otherwise when the application runs, it won't find it.
You just checked your connection string to be null. Check string.IsNullOrEmpty() to see if it's not null. Besides, you need to set breakpoint and check if the connection string value you see in your app.config actually retrieved in your code and it is correct.
I got two problems:
First, i'm trying to connect my windows form app with my embedded database (.dbf) and i keep getting this message no matter what i do to the connection string:
"error isam instalable cant be found"
Second, i would like to make the path relative to the executable.
Thanks, here is the code i'm using to test the whole thing:
private void bGuardar_Click(object sender, EventArgs e)
{
try
{
string cadena = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =D:\\; Extended Properties = dBASE IV; UserID =; Password =;";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = cadena;
con.Open();
MessageBox.Show("conected");
con.Close();
}
catch (OleDbException exp)
{
MessageBox.Show("Error: " + exp.Message);
}
}
For the second part, you can get the path of your executable using System.IO.Path.GetDirectory(Application.ExecutablePath). There are more ways do this based upon your need (see Best way to get application folder path).
To avoid further difficulties instead of
'OleDbConnection con = new OleDbConnection();'
try
using (OleDbConnection con = new OleDbConnection())
{
; // your command and executes here
}
this way you call the dispose / close method always (using generally wraps up your code so that the part between { and } is wrapped in a try / catch block with finally that calls a dispose() / close() on the OleDbConn object.
I am using the following code to connect to sql throgh windows authentication.
string connctionstring = "connectionString={0};Database={1};Integrated Security=SSPI;";
string _connctionstring = string.Format(connctionstring, datasource, initialCatalogue);
SqlConnection _connection = new SqlConnection(_connctionstring);
_connection.Open();
But i am getting the following error. Help please.I am able to login through sql server.
The connection string format is not correct
Change to this:
string connctionstring = "Data Source={0};Database={1};Integrated Security=SSPI;";
Or
string connctionstring = "Server={0};Database={1};Integrated Security=SSPI;";
While Peyman's answer does cover the basic issue (connectionString is not a valid key for the string) a better solution is to use a SqlConnectionStringBuilder, this will also help you do proper escaping if you have odd characters in your string (for example if your database name contained a space)
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = datasource;
scsb.InitialCatalog = initialCatalogue;
scsb.IntegratedSecurity = true;
//You also really should wrap your connections in using statements too.
using(SqlConnection connection = new SqlConnection(scsb.ConnectionString))
{
connection.Open();
//...
}