I'm new to c# and im trying to make a store bill generator for fun and learning. Since I don't know much about databases Access seemed decently simple.
I'm just trying to give user confirmation that the connection to the db is successful, I've connected the db to my project but when I run the program nothing happens
I've tried giving the status in a label but it doesn't show either.
availableproductsbox is a listbox
private void availableproductsbox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\source\repos\MultiCashTrack\MultiCashTrack\items.accdb;
Persist Security Info=False;";
connection.Open();
MessageBox.Show("Database connected");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Database connection failed"+ ex);
}
}
I expect it to show a message box showing "Database connected" but it doesn't show
Related
I'm very new to coding, and recently got a task to connect my SSMS/SWL Database to Visual Studio 2019.
When I press the button, the DB should connect and a message should pop up saying it's been connected.
I assume I have the incorrect login details, but I'm not sure, and even if I was sure, I wouldn't know how to find the correct login details.
So here's my current button click code:
private void button1_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=TRISTAN\SQLEXPRESS ;Initial Catalog=TutorialDB ;User ID=TRISTAN\Tristan; Password=";
cnn = new SqlConnection(connectionString);
cnn.Open();
MessageBox.Show("Connection Open");
cnn.Close();
}
So, the login detail's I'm using are those shown when launching SSMS and the "Connect to Server" box pops up.
Am i using the login details from the correct place "Connect to server window" Or are the details I need somewhere else.
The error message I get when clicking the 'Connect' button "System.Data.SqlClient.SqlException: 'Login failed for user 'TRISTAN\Tristan'.'"
I'd appreciate any assistance, please also keep in mind I don't know much Programming language yet, so please keep it simple.
Open Visual Studio
Go to View tab -> Server Explorer
Right click to "Data Connections" tab
Add connection
Select the server name
Select the database
Ok
Server Explorer -> Data Connections -> myServer\myDB.dbo -> right click and then Properties
Copy the connection string from Properties View
Write this code;
string connectionString;
SqlConnection cnn;
connectionString = #"***YOUR_CONNECTION_STRING***";
cnn = new SqlConnection(connectionString);
cnn.Open();
if (cnn.State == System.Data.ConnectionState.Open)
{
MessageBox.Show("Connection Open");
cnn.Close();
}
if (cnn.State == System.Data.ConnectionState.Closed)
{
MessageBox.Show("Connection Closed");
}
You should catch error while opening a connection and display it to the user, something like this:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=TRISTAN\SQLEXPRESS;Initial Catalog=TutorialDB;Trusted_Connection=True;";
using (var cnn = new SqlConnection(connectionString))
{
try
{
cnn.Open();
MessageBox.Show("Connection Open");
}
catch (SqlException ex)
{
MessageBox.Show("Error while connecting to database: " + ex.Message);
}
finally
{
cnn.Close();
}
}
}
when i tried to run this program in visual studio 2010 its shows an error. Like this "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)"
public partial class tcregistration : Form
{
SqlConnection conn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/dce 3/documents/visual studio 2010/Projects/TC_Maker/TC_Maker/TC_REG.mdf;Integrated Security=True;User Instance=True");
public tcregistration()
{
InitializeComponent();
}
private void insert_Click(object sender, EventArgs e)
{
string gender = string.Empty;
if (rbmale.Checked)
{
gender = "M";
}
else if (rbfemale.Checked)
{
gender = "F";
}
string tcrecieved = string.Empty;
if (rbyes.Checked)
{
tcrecieved = "Y";
}
else if (rbno.Checked)
{
tcrecieved = "N";
}
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand ("TCAddorUpdate",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode","Add");
cmd.Parameters.AddWithValue("#tcnumber",txttcno.Text.Trim());
cmd.Parameters.AddWithValue("#name",txtname.Text.Trim());
cmd.Parameters.AddWithValue("#dob",dtpdob);
cmd.Parameters.AddWithValue("#religion",txtrelig.Text.Trim());
cmd.Parameters.AddWithValue("#caste",txtcaste.Text.Trim());
cmd.Parameters.AddWithValue("#sex",gender);
cmd.Parameters.AddWithValue("#doa",dtpdoa);
cmd.Parameters.AddWithValue("#regno",txtregno.Text.Trim());
cmd.Parameters.AddWithValue("#dor",dtpdor);
cmd.Parameters.AddWithValue("#dept",txtdept.Text.Trim());
cmd.Parameters.AddWithValue("#sem", combosem);
cmd.Parameters.AddWithValue("#ifqulify",txtqualified.Text.Trim());
cmd.Parameters.AddWithValue("#conduct",txtconduct.Text.Trim());
cmd.Parameters.AddWithValue("#applieddate",dtpdoapp);
cmd.Parameters.AddWithValue("#ifrecieved",tcrecieved);
cmd.Parameters.AddWithValue("#receiveddate",dtpdor);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error Message");
}
finally
{
conn.Close();
}
}
}
}
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)
This is not a programming Problem, but a networking/connection string one.
Connection Strings are their own area of experetise, way outside the normal programmers knowledge. Luckily there is a page for it: https://www.connectionstrings.com/sql-server/
It turns out even when attaching, you have to supply a database name: "Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection."
And as others mentioned, you got the wrong kind of slashes too.
Pretty off topic, but exception handling is a pet peeve of mine. And yours has some of the serioues mistakes. Like catching exception and only exposing the message. Those are 2 Cardinal sins. Thee are two article on the thematic I link often:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I have some problems with connecting to my Microsoft SQL Server 2012. Here is my code:
private void conButton_Click(object sender, EventArgs e)
{
string conString;
SqlConnection appMessage;
conString = #"Data Source=DHRANTONIUSVICT\SQLA; Initial Catalog=AppMessage; User ID=myid; Password=mypass; Server=localhost\sqlexpress";
appMessage = new SqlConnection(conString);
try
{
appMessage.Open();
MessageBox.Show("Connection is stable. Starting up the engines...");
}
catch (Exception)
{
MessageBox.Show("Connection to HQ is unstable. Need engineers ASAP!");
}
Somehow I can't connect to my SQL Server.
What am I doing wrong?
And please, bare in mind that I`m new to this SQL stuff.
Use DataSource or Server.You are using both
conString = #"Data Source=DHRANTONIUSVICT\SQLA; Initial Catalog=AppMessage; User ID=myid; Password=mypass ";
please refer to the SqlConnection.ConnectionString documentation:
I am creating connection with my online mysql database but it gives me the error (unable to connect to any of the specified Mysql hosts).
this is my code:
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection con1 = new MySqlConnection("Server=http://eu5org.freewebhostingarea.com; Port=3306; Database=477928; Uid=477928; Pwd=password123;");
con1.Open();
MessageBox.Show("Connection Established");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
how could i correct this?
It seems that the hosting you have only allows a server address of localhost any other address will fail.
I created a connection with a Microsoft sql database and am trying to add basic informastion as part of an exercise but get the following error.
Object reference not set to an instance of an object
This is how I connect to the database
SqlConnection sqlConn;
protected void butConnect_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=lrmg;Integrated Security=True;";
sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
labMessage.Text = "a connection to your database was established";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Here is where I get the error
protected void butSubmit_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string date = txtDate.Text;
**SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES('" + name + "'," + date + ")";
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
}
I am under the impression that the sql connection was opened so why the exception?
You are getting the error because reference variable sqlConn is null - that is happening probably because
From you code snippet, connection is getting created and opened in
connect button click. So you need to hit connect before submit
Most likely cause is probably different assuming that this ASP.NET code - in such case, every request is served by different instance of page class - so if you open connection on one request (connect click), it (that variable) won't be available in next request (submit click). The remedy is simple - create and open connection when you need it i.e. in submit click. On the other hand, you probably need to understand mode about web programming models to avoid such mistakes.
You use two different events to do your work on the database. Why? Have you ever heard of connection pooling?
Probably between the first event (open connection) and second event (db insert) something happens and change your global variable SqlConn to null and you get the error. (Of course I am assuming that you press that button to open the connection before trying to insert anything)
With connection pooling this kind of programming pattern is no more necessary, instead, when you need to update/insert/delete/select something you open the connection, do your work and close immediately the connection without keeping it open and consuming resources on the server and client side.
try
{
string connectionString = "Data Source=.\\SQLEXPRESS;" +
"Initial Catalog=lrmg;Integrated Security=True;";
using(SqlConnection sqlConn = new SqlConnection(connstring))
{
SqlCommand cmd = sqlConn.CreateCommand();**
cmd.CommandText = "INSERT INTO Canditate(Name, Doj) VALUES(#name, #dt)";
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#dt", Convert.ToDateTime(txtDate.Text));
cmd.ExecuteNonQuery();
labMessage.Text = "The value was inserted into your database";
}
}
catch (SqlException sqlE)
{
labMessage.Text = sqlE.Message;
}
catch (Exception exe)
{
labMessage.Text = exe.Message;
}
Notice also that your code is subject to Sql Injection attacks because you use string concatenation to build your sql text. This is a bad practice that should be avoided at all costs
You should have a dedicated method to open the connection, that you'd invoke every time you're using the connection. With your current setup, butConnect_click MUST be called before butSumbit_Click in the same request. So add the call to butConnect in butSubmit.