I'm really new to using databases with Windows WPF applications and am getting an error message as follows -
Format of the initialization string does not conform to specification starting at index 0.
I am unsure as to why this error is occurring and was wondering if anyone could help solve it?
The code I've used to try and connect to the database:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DataSet dataset = new DataSet();
private void Item_List_Loaded(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"F:\VS Projects\POS applicarion\POS applicarion\Imes.sdf");
SqlDataAdapter adapt = new SqlDataAdapter(conn.CreateCommand());
adapt.SelectCommand.CommandText = "select * from item";
adapt.Fill(dataset);
PopulateListBox();
}
}
Thanks!
As the comment in your question, the connection string is wrong.
You must supply the SqlConnection's constructor parameter with the correct syntax of SQL Server connection string.
For example:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Please visit http://www.connectionstrings.com/sql-server/ for more syntax samples of connection strings.
Related
CONTEXT: I am writing a WPF app. It works with a SQL Server database in which I put some data, concretely the strings Titulo and Descripcion, the int XP and the string fotoMision. When I click a button the program is supposed to save this data in the database.
PROBLEM: when I click the button it throws me an exception in string connection's line showing that the object is not instanced. If I put these first lines right below the InitializeComponent(); line the second one doesn't recognise the miConexion string. Why does that happen and how can I fix it?
CODE:
static string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
SqlConnection miConexionSql = new SqlConnection(miConexion);
private void Button_Click(object sender, EventArgs e)
{
string consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
SqlCommand miSqlCommand = new SqlCommand(consulta, miConexionSql);
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
Connections are meant to be short-lived, i.e. you should create one when the button is clicked and then dispose it right after you have executed the query. Using a using statement implicitly disposes the IDisposable:
private void Button_Click(object sender, EventArgs e)
{
const string Consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
using (SqlConnection miConexionSql = new SqlConnection(miConexion))
using (SqlCommand miSqlCommand = new SqlCommand(Consulta, miConexionSql))
{
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
}
The format of your connection string for a SQL Server Database should be like so:
"Data Source=DNS_or_IP_Address;Initial Catalog=DatabaseName;User Id=MyUser;Password=MyPassword"
Connection Strings and Examples for various databases
put connectionstring on form_load event
I am beginner at SQL and thank you for your attention. I've created a database (by using "Add new Item" from "Project" menu and adding a "Service Based Database") in Visual Studio 2015 and now I want to connect to it and read or write data on it.
But I don't know how to connect to it by code.
I use the string showed in the connection string when I click on the database in server explorer.
That is here:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf";Integrated Security=True
But as you know, it cannot be used when I copy and paste it to a string thah can be used in new sqlConnection(connection string), because this string has '\' or ' " '
What's the right string for me to connect to this local database?
Now this is my code but it is not useful:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True");
con.Open();
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
SqlCommand cmd = new SqlCommand(t, con);
cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True"))
{
con.Open();
string t = "SELECT * From Table";
SqlCommand cmd = new SqlCommand(t, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader["Id"].ToString() + reader["name"].ToString());
}
con.Close();
}
}
Thank you for your help
Update: I get another errors in writing and reading table
I think I've connected to my database after using your help. and now I have another error in reading the table. this error points to
SqlDataReader reader = cmd.ExecuteReader();
in my code and says:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
and an error in writing on table points to
cmd.ExecuteNonQuery();
in my code:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
My database has one table named Table that contains two columns: Id(int) and name(nchar10)
The code you're using to connect to your Sql db is .. well ... really old school. We just don't do it like that any more.
So - what can we do instead? Lets use a nice library called Dapper which makes 'talking' to a sql server really easy, simple and safer.
First, install the package Dapper from nuget:
Create a POCO which will represent the data that is returned from the DB.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Now update the form code as follows:
private const string _connectionString = #"Data Source = (LocalDB) <snipped..>";
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (Id,name) Values (34, 'John')";
int rowsInserted;
using (var db = new SqlConnection(_connectionString))
{
rowsInserted = db.Execute(query);
}
if (rowsInserted != 1)
{
// Log/Handle the fact that you failed to insert 1 record;
}
}
private void button2_Click(object sender, EventArgs e)
{
IList<Foo> foos;
using (var db = new SqlConnection(_connectionString))
{
const string query = "SELECT * FROM Table";
// This will always return a list. It's empty or has items in it.
foos = db.Query<Foo>(query).ToList();
}
foreach(var foo in foos)
{
MessageBox.Show($"{foo.Id} - {foo.Name}");
}
}
Is that much cleaner? Yep - I thought so.
Of course, I would never put database code behind a winform event but into a dedicated class, etc. But I guess you're just learning/playing around/experimenting :) :)
Also, I've not put error handling in there, to keep the example smallish.
Change:
string t = "SELECT * From Table";
to:
string t = "SELECT * From [Table]";
and:
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
to:
string t=#"INSERT INTO [Table] (Id,name) Values (34, 'John')";
See https://stackoverflow.com/a/695590/34092 and https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql .
my problem has been solved
at first for connection to database I typed an # before connection string and deleted the quotes inside the string as #juergen d said in comments
at second for solving the error in writing and reading the table I typed [ and ] before and after the "Table" as #mjwills said
also #Pure.Krome explained a more professional way to improve the code
thank you every body
I have problem with connecting a database to my UWP.
public sealed partial class MainPage : Page
{
string connstring;
public MainPage()
{
this.InitializeComponent();
connstring = #" Data Source = tcp:stdgydlcdk.database.windows.net;Initial Catalog=doc4cloud_db;User ID=****;Password = ****; version = 3";
}
private void Add_Click(object sender, RoutedEventArgs e)
{
using (SqliteConnection con = new SqliteConnection(connstring))
try
{
con.Open();
if(con.State == System.Data.ConnectionState.Open)
{
NewBlogUrl.Text = "succes";
}
}
catch(Exception ex)
{
NewBlogUrl.Text = ex.Message +ex.InnerException;
}
}
}
(instead of stars in connection string, I have valid ID and password)
As you can see in my simple test program here, I am trying to make a connection to a database and print stuff depending on result. The poject runs how it is supposed to but the problem comes when the click action is called. First exception is a ArgumentException, which say that keywords Initial Catalog= , User ID= , Password = and version = ,from my connection string ,are not supported,and if I remove one of them, the Exception is thrown for the next one, the second problem is, if I remove all of them(even if I should not), I get rid of ArgumentException but, I get a connection exception now, The given path's format is not supported to be more specific. I have all necesary dlls
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source = tcp:stdgydlcdk.database.windows.net;Initial Catalog=doc4cloud_db;User ID=****;Password = ****; version = 3");
}
Here I made a model to get acces to my database. Maybe I did something wrong in my model, maybe connection string declaration is wrong, I am not sure. Any feedback is welcome. Thank you very much in advance.
I'm a beginner.
I already found a way to connect to SQL SERVER using the codes below:
private void getListBtn_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=myDB;Integrated Security=true;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT ID,Date,Name,City FROM Info;", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridForm.ItemsSource = dt.DefaultView;
I also wanted to get number of rows from a TABLE and set it to a label, But it's not a good idea to copy and paste this code again, I want to have a method for sqlconnection so i won't rewrite this code again and again for every single query.
Sorry i'm an absolute beginner, 3 days since i started learning C# WPF.
Yes some frameworks and/or ADO's solutions are good and maybe the best "professionnal" approch, you say you're a beginner and I was it not so far ;-).
So the simpliest way is to add a new class for the sql connection. In example add a Sqlconnect.cs class.
using System.Data.SqlClient;
public class Sqlconnect
{
public SqlConnection Con { get; set; }//the object
private string conString { get; set; }//the string to store your connection parameters
}
This class will have a method to open the connection and one to close it.
public void conOpen()
{
conString = "Data Source=..."; //the same as you post in your post
Con = new SqlConnection(conString);//
try
{
Con.Open();//try to open the connection
}
catch (Exception ex)
{
//you do stuff if the connection can't open, returning a massagebox with the error, write the error in a log.txt file...
}
}
public void conClose()
{
Con.Close();//close the connection
}
In your other(s) classe(s) where you need a sql query you first instantiate an new object.
private void getListBtn_Click(object sender, RoutedEventArg e)
{
Sqlconnect con = new Sqlconnect();//instantiate a new object 'Con' from the class Sqlconnect.cs
con.conOpen();//method to open the connection.
//you should test if the connection is open or not
if(con!= null && con.State == ConnectionState.Open)//youtest if the object exist and if his state is open
{
//make your query
SqlDataAdapter sda = new SqlDataAdapter("your query", con);
//etc
con.conClose();//close your connection
}
else
{
//the connection failed so do some stuff, messagebox...as you want
return;//close the event
}
}
this example need some ameliorations, it's evident but I wrote it like this to be clearest.
First thing this is not related to WPF, this is general coding even I would not consider this to be related to .net.
For your current problem to show the count, you dont have to make a call again. You can get the count from the datatable row count. But, I would suggest few things:
You should have one or different separate layers like business, data access etc. as per your needs.
You should not give the connection as the way you have provided here.
You can choose to use any ORMs like entity framework, NHibernate etc based on your needs. This just a direction, you can choose to stick with ADO.Net as you have it your choice. But I would definitely suggest to throw in more layers to avoid duplicate codes and more structured approach.
Best choice if you don't need so much performance is ORM like Entity Framework.
Here is something of basics.
Just use it like in MVC app.
If we copy paste your code, then the error is appearing. I have corrected it and maybe others don't need to struggle like me to find this. :)
// Object exists and State is open
if (Conex != null && Conex.Con.State ==
System.Data.ConnectionState.Open)
{
// Create a String to hold the query
string query = "insert into Xray_Table values
(25,'zzz','hij',3,'uuu',6,'2012-06-18
10:34:09.000')";
// Create a SqlCommand object and pass the constructor the connection string and the query string
SqlCommand queryCommand = new SqlCommand(query, Conex.Con);
// Execute the query to update to the database
queryCommand.ExecuteNonQuery();
// method to close the connection.
Conex.conClose();
}
This is my simple Code which stores parameters value in variables and use it on query
but it's give me ERROR message "INVALID Object name "DTA010.DFDR00" because I guess i'm not connected with the AS/400
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string strQuery;
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("\n");
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
Response.Write("Your Order Status is");
Response.Write(niceMethod1());
Response.Write("\n");
}
public string niceMethod1()
{
string tDate = "";
string nOrder = (Request.QueryString["order"] ?? "0").ToString();
using (SqlConnection connection = new SqlConnection("Data Source=*****;User ID=web;Password=****;Initial Catalog=WEBSTATUS;Integrated Security=False;"))
{
string commandtext = "SELECT A.STAT01 FROM DTA010.DFDR00 AS A WHERE A.ORDE01 = #nOrder"; //#nOrder Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
//command.Parameters.AddWithValue("#nPhone", nPhone); //Adds the ID we got before to the SQL command
command.Parameters.AddWithValue("#nOrder", nOrder);
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
}
The drivers needed to connect from a .NET application to a AS/400 are properly installed.
If the names of the schema (aka library) and table (aka file) are spelled correctly, try replacing the period with a slash /. This would be used for "system" naming syntax, rather than "standard" naming syntax.
You are definitely connected. I think the issue may be in the error you received. Make sure that the object exists that you are connecting to. WRKOBJ OBJ(BTGDTA010/DF01HDR00) will see if it exists. Check that everything is spelled right. It might be a typo.
Here is the simplest way I Found may be useful for someone..!!
First need to add Assembly IBM library and
using IBM.Data.DB2.iSeries;
then
iDB2Connection connDB2 = new iDB2Connection(
"DataSource=158.7.1.78;" +
"userid=*****;password=*****;DefaultCollection=MYTEST;");