Can't make a connection to database in UWP project using SQLite - c#

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.

Related

connectionString, i need to use password, but i'm using windows connection

I have created a database with visual studio, i'm using windows authentication to connect to it.
I've tried many things but it's not working
namespace Stock
{
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=false";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
connexion_BDD();
string request = "SELECT ref_pdt FROM produits";
SqlCommand command = new SqlCommand(request, connexion_BDD());
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
I have an error on dataReader because the connection is currently closed
I literally just banged this out, but you will want something like this: (Hint: Take a look at something like Dapper as you may like that better)
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=true";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
using (var connection = connection_BDD())
{
string request = "SELECT ref_pdt FROM produits";
using (var command = new SqlCommand(request, connection))
{
using (var dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
}
}
Edit: Just in case I am misreading your question to mean that you really want to be connecting using a username and password, then make the connection string this:
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;User Id=YOURUSERNAME;Password=YOURPASSWORD;Trusted_Connection=false";
Edit: To setup SQL credentials (I do not really recommend this as I think integrated security is better as it avoids username/password credentials leaking into source control):
Make sure SQL Server Authentication is enabled (SSMS -> Server
(Right-Click) -> Properties -> Security (Make sure the second radio
button is selected "SQL Server and Windows Authentication Mode"
You will need a server login and mapped DB user. Under the server
(in SSMS), expand Security -> Logins. Add a login (Right-click login
choose Add Login).
Enter the login name you want (this is the
User Id in the connection string) and select SQL Server
Authentication, then pick a (hopefully good) password. If this is a
local box and you don't care turn off the password policy
checkboxes.
In the dialog under Database Roles leave public or
make it more privileged if you want it to manage DBs. If this is a
local devbox making the account sysadmin can be OK.
In the dialog under User Mapping, select your DB and select appropriate
roles. If the user just needs to access (read/write) data, pick
db_datareader/db_datawriter. Often on a dev box just picking
db_owner is best (if you are managing schema, etc.)

c# odbc update query doesnt work properly

Hi I'm having a lot of truble doing a program in c#
i have to connect to SQLANYWHERE 11 and do an update to a table
could u tell me where I'm wrong?
program go well until i reach the:
int number = wCommand.ExecuteNonQuery(); line
the program doesnt crash but tables get not updated
string dns = "Dsn=dattest;Uid=******;Pwd=******;";
OdbcDataReader reader;
OdbcCommand wCommand;
ODBCClass dst1 = new ODBCClass(dns);
queryins = "UPDATE dba.Sala_export_dati_macchina_produzione SET stato='p'";
// +"WHERE id_prd_lav_ord_lav='"+ id_prd_lav_ord_lav + "'";
wCommand = dst1.GetCommand(queryins);
int number = wCommand.ExecuteNonQuery();
Console.WriteLine("executed "+ number);
this is the odbc class that i'm using
public class ODBCClass
{
OdbcConnection oConnection;
OdbcCommand oCommand;
public ODBCClass(string DataSourceName)
{
oConnection = new OdbcConnection(DataSourceName);
try
{
oConnection.Open();
System.Diagnostics.Trace.WriteLine("Connessione stabilita con il database " + DataSourceName);
}
catch (OdbcException caught)
{
System.Diagnostics.Trace.WriteLine(caught.Message);
}
}
public void CloseConnection()
{
oConnection.Close();
}
public OdbcCommand GetCommand(string Query)
{
oCommand = new OdbcCommand
{
Connection = oConnection,
CommandText = Query
};
return oCommand;
}
public void Dispose()
{
oConnection.Close();
}
}
EDIT
just in case i've tried to change connection string with this pattern:
#"Driver={SQL Anywhere 11};DatabaseName=my_db_name;EngineName=my_server_name;uid=username;pwd=password;LINKs=tcpip(host=host_ip_address)"
and always the system gave me no error on connection in both cases
Ok guys that was kinda strange.
Let me explain the whole thing. I was doing that program for a customer that asked a software which could link my mysql db and a sybase db of another company.
The problem was that the DBMS of that company when is opened on the server block all kind of external editing to the db with which is connected.
So select query worked regularly but update and insert were blocked by that client...
I've passed 4 day with a perfect working program but that company didn't told me this "little" thing.
So be aware of DBMS they are cruel.

Syntax of SQL Server database connection string in c#

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

Error when accessing database

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.

How Can I connect AS/400 from MY simple ASP.net and C# program Which Take parameters from URL

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;");

Categories

Resources