Hello guys i've been stuck here for 2 days. I want when i full in my textboxes that the text will go to my database "loonberekening into my table werknemer".
But now im getting this
error: An unhandled exception of type 'System.ArgumentException'
occurred in System.Data.dll
Additional information: Keyword not supported: 'integrated security'.
and he is ticking this line: SqlConnection cnnLoonberekening = new SqlConnection(database);
Thanks for helping me and here is my code!
private void btnOpslaanwerknemergegevens_Click(object sender, EventArgs e)
{
string database = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30;InitialCatalog=loonberekening";
string werknemergegevens = "insert into loonberekening.werknemer (naam,voornaam) values ('"+this.txtNaam.Text+"','"+this.txtVoornaam.Text+"');";
SqlConnection cnnLoonberekening = new SqlConnection(database);
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
SqlDataReader check;
try{
cnnLoonberekening.Open();
check = scmdLoon.ExecuteReader();
MessageBox.Show("Opgeslagen");
while (check.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Please set the correct connection string like this
// SQL Connection String with |DataDirectory| substitution string
SqlConnection c = new SqlConnection (
#"Data Source=.; AttachDbFilename=|DataDirectory|\loonberekening.mdf;Initial Catalog=loonberekening");
Related
Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.
I have a FastHost server with a database.
I've just put in an example IP but i have been using the one given on my control panel on the site.
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012" +
"Initial Catalog = DiscoverThePlanet" +
"User ID = TestUser" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
This returns the
Can not open Connection!" message.
I get the following show in my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.
You're missing a couple of ;
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as #Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string
concatenation is used to build connection strings that are based on
user input. If the string is not validated and malicious text or
characters not escaped, an attacker can potentially access sensitive
data or other resources on the server. For example, an attacker could
mount an attack by supplying a semicolon and appending an additional
value. The connection string is parsed by using a "last one wins"
algorithm, and the hostile input is substituted for a legitimate
value.
The connection string builder classes are designed to eliminate
guesswork and protect against syntax errors and security
vulnerabilities. They provide methods and properties corresponding to
the known key/value pairs permitted by each data provider. Each class
maintains a fixed collection of synonyms and can translate from a
synonym to the corresponding well-known key name. Checks are performed
for valid key/value pairs and an invalid pair throws an exception. In
addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>
Add a semicolon after each part of your connection string code:
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
https://www.connectionstrings.com/sql-server/ should tell you more about the correct format.
Your connectionstring is not well formated, you forgot some ; :
"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test"
An example :
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
https://www.connectionstrings.com/sql-server/
There are some ';' missing. Try this:
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
Use StringBuilder if you wants to write ConnectionString like mention,
String object it will occupy memory each time.
StringBuilder will occupy memory only once, so it will give you better performance.
SqlConnection conn = new SqlConnection();
StringBuilder sb=new StringBuilder();
sb.Append("Data Source = 123.456.789.012;");
sb.Append("Initial Catalog = DiscoverThePlanet;");
sb.Append("User ID = TestUser;");
sb.Append("Password = Test;");
conn.ConnectionString =sb.ToString();
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
Semi Column is missing in the Connection String. So correct it
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
I've tried to establish a connection between my MS Access database and my c# application and I am not understanding why I am getting this error when the filename is correct.
Any
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sQTDBDataSet.tblEquipment' table. You can move, or remove it, as needed.
this.tblEquipmentTableAdapter.Fill(this.sQTDBDataSet.tblEquipment);
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Owner\Documents\Visual Studio 2015\Projects\Application\Application\bin\Debug\SQTDB.accdb;Persist Security Info=False;";
connection.Open();
checkConnectionLabel.Text = "Connected.";
connection.Close();
}
I'm new into c# programming and I'm trying for a while to debug this but so far I found no answer that could help me.
I'm trying to add a new record into a MSSQL database and I get the following error each time:
{"Input string was not in a correct format."}
My code is below:
private void btnAdd_Click(object sender, EventArgs e)
{
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
string insert = "INSERT INTO Companii (IDCompanie, Denumire, Adresa, Oras, CUI) VALUES (#IDCompanie, #Denumire, #Adresa, #Oras, #CUI)";
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#IDCompanie", txtID.Text);
cmd.Parameters.AddWithValue("#Denumire", txtDenumire.Text);
cmd.Parameters.AddWithValue("#Adresa", txtAdresa.Text);
cmd.Parameters.AddWithValue("#Oras", int.Parse(cmbOrase2.SelectedValue.ToString()));
cmd.Parameters.AddWithValue("#CUI", txtCUI.Text);
int val = cmd.ExecuteNonQuery();
MessageBox.Show(val + "Compania a fost adaugata cu succes!");
con.Close();
this.Dispose();
}
}
catch (Exception er) { MessageBox.Show(er.Message); }
}
The combobox Orase2 is binded with some values from a MSSQL database. Please, need some help! Thanks.
I have changed the combobox.ValueMember and it worked. I was converting to string when in fact I already had the int value.
I'm trying to connect to a local database (service-based database created in Visual Studio 2013).
I use this C# code:
string connectionstring = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"|DataDirectory|\\InvDB.mdf\";Integrated Security=True";
public int testpripojeni()
{
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand();
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
}
This function should connect to the database and count rows in table HlavniTab. But I get error on line
int pocet = (int)prikaz.ExecuteScalar();
It says
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteScalar: Connection property has not been initialized.
What should I do to fix it?
your sqlcommand was not assigned a connection
try
prikaz.Connection = pripojeni;
Connection property in SqlCommand must have to be populated. You can set the connection property using Constructor and also directly set the value to Connection property.
Try -
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand(pripojeni);
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
or
using(SqlConnection pripojeni = new SqlConnection(connectionstring))
{
pripojeni.Open();
SqlCommand prikaz = new SqlCommand();
prikaz.Connection = pripojeni;
prikaz.CommandText = " SELECT COUNT (*) FROM HlavniTab";
int pocet = (int)prikaz.ExecuteScalar();
pripojeni.Close();
return pocet;
}
hello am working on back up access database using C#, i have four groups which is access configuration , database selection, database backup and database restore.
so on data configuration i have data source textbox user id textbox and password textbox on database selection i have database combbox so that i can select one so i wrote this code
public partial class Form11 : Form
{
private OleDbConnection conn;
private OleDbCommand command;
private OleDbDataReader reader;
string ole = "";
string connectionString = "";
public Form11()
{
InitializeComponent();
}
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";
conn = new OleDbConnection(connectionString);
conn.Open();
ole = "EXEC sp_databases";
command = new OleDbCommand(ole, conn);
reader = command.ExecuteReader();
cmbDatabases.Items.Clear();
while (reader.Read())
{
cmbDatabases.Items.Add(reader[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
the problem is i keep seeing object reference not set to an instance of an object, here i use access database but on SQL i didn't have such problem, please help me out with this thing.
thank you.
Conn is an object and is not instantiated yet when you are using conn.ConnectionString property
just flip the order this 2 lines
try
{
conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";
In your code, you are using your connection before instantiating your connection object. You need this first:
conn = new OleDbConnection();
The error should have referenced a line in your code that you were getting this problem - often relatively easy to track back from there to see what is null.