I want to ask about connecting db with c#.
I have read http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm and written my code, but the connection doesn't seem to be working.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=localhost;Initial Catalog=dbabc;User ID=admin;Password=qwerty";
sql = "UPDATE ppd,brg,cmp SET WHERE";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Did I write something wrong? The error message shown always says "Can not open connection"!
The Exception thrown should be a SqlException. Check the ErrorCode on the SqlException and look it up here...
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
Rather than catch(Exception ex) your code should do this...
try
{
connection.Open();
....
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Can not open connection ! Error: {ex.Message}");
}
I think you should check server name
if you install SQL server (Standard) on your computer, server name named is (local) or .
If you are using VS create a data source and test the connection string. Go to data> Add new data source. There is find your database server and create the correct string.
Your code is working. I can verify it. Please check your connection string and SQL query. Especially your SQL query. It seems to be wrong.
Try to execute the query in Microsoft SQL Server Management Studio. If there is an error in your query, you can easily find it there.
SQL Update Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Recommended Readings
https://www.tutorialspoint.com/sql/sql-update-query.htm
https://www.w3schools.com/sql/sql_update.asp
To verify the connection string,
Open the Server Explorer pane. ("View" menu, "Server Explorer" or
use the key shortcut CTRL+Alt+S).
Right-click on the Data Connections, Select Add connection and then
press continue after selecting Microsft SQL Server as the Data source.
Select Refresh and click down arrow and then select your SQL server.
If you cannot find it, enter the server name manually.
You may also have to enter the SQL server credentials.
Select or enter your database name & then press Test Connection.
If you see a Test connection succeeded message, then your SQL server is working.
If you want, you can also get connection string by pressing Advanced.. button and then copying the connection string
In addition, try to an add exception message to catch block. That way, you can easily find the error.
MessageBox.Show("Can not open connection ! \n" + ex.Message);
Related
How would I go about to do a bulk record delete on a .TPS database?
I've been trying with the ODBC V4 Topspeed driver in C# but each time I execute the delete command the program would just start hanging or if I add code to close the db (cnn.Close()) after the cmd.ExecuteNonQuery() method, the program crashes with the following error: The program '[12345] abcdefg.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.. Note: Topscan is closed while performing these operations. (I have had success with SELECT queries so the connection string and so on is correct)
Example of the SQL command via the ODBC Topspeed driver: "DELETE FROM table WHERE column = '12345'"
Example of delete command:
public void deleteCommand(string sqlCommand)
{
try
{
string connectionString = database_a_string;
OdbcConnection cnn = new OdbcConnection(connectionString);
cnn.Open();
OdbcCommand cmd = new OdbcCommand(sqlCommand, cnn);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Topspeed error: " + ex, "Delete Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Maybe I could use Topscan instead? But I have only seen a way to delete records individually. This DB has over 900 000 records.
Edit: I was able to execute an insert command successfully with the same method format. I have a hunch the OBDC V4 Topspeed driver is causing the "Access Violation" error.
I am very new in C# and now try to find online resource to connect VS C# to mySQL database at server 'localhost', with userid 'root', and password '****', the databasename is 'dlht'.
1.I copied a line of code from youtube and it works:
this.stockTableAdapter.Fill(this.blhsDataSet.stock);
Can anyone explain to me what exactly this is doing? There is no place to put server, password, userid etc... How can it work?
I tried to use the online tutorials to connect to mySQL database
ZetCode C#Tutorial
string cs = #"server=localhost;userid=root;
password=****;database=dlht";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
I run this code at Form1.cs at VS C#. It is always stuck at :
conn = new MySqlConnection(cs);
Why? Thank you so much!
It seems that the proper way to connect to MySql database is this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
I develop a programe use c# Framework2.0 and Database is mysql.
I use transaction but always has error
System.InvalidOperationException: Connection must be valid and open to rollback transaction
at MySql.Data.MySqlClient.MySqlTransaction.Rollback()
Here is some of source code:
try
{
using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
connection.Open();
MySqlCommand command = connection.CreateCommand();
MySqlTransaction myTrans = connection.BeginTransaction();
command.Connection = connection;
command.Transaction = myTrans;
try
{
string sql ="XXXXX";
command.CommandText =sql;
command.ExecuteNonQuery();
sql="yyyy";
command.CommandText =sql;
command.ExecuteNonQuery();
.........
myTrans.Commit();
}
catch (Exception ex)
{
myTrans.Rollback();
throw ex;
}
}
}
catch (Exception ex)
{
FileHelper.WriteLog(ex);
}
I check the sample from:
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqltransaction.html
The source code should be ok.
The error said the connection seems close already.
I think use Using() should be ok. it will close automatically.
Can Some help me with this?
Finally I find the solution .
The MySqlCommand.CommandTimeout default is 30 seconds.
maybe the server is old and data is big.
so timeout
so show error
Connection must be valid and open to rollback transaction
Just Set MySqlCommand.CommandTimeout=1200
this one can work fine.
it's really hard to find the root cause.
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.
Im using the code below, to update a record in an MS Access database, to store some information related to a property grid, however, im receiving a syntax error when the query tries to execute, and i cannot figure out why. ConnCheck simply looks to see if the connection is open, and if not, it opens it.
Thanks in advance
Main_Class.ConnCheck();
OleDbCommand cmd = new OleDbCommand("UPDATE [CALCULATION_RUN_TBL] SET [CAP_INPUTS]=?, [RA_INPUTS]=?, WHERE [CALCULATION_RUN_ID]=?", Main_Class.con);
try
{
cmd.Parameters.Add("#CAP_INPUTS", OleDbType.LongVarBinary).Value = SaveCAPSettings();
cmd.Parameters.Add("#RA_INPUTS", OleDbType.LongVarBinary).Value = eig.SaveSettings();
cmd.Parameters.Add("#CALCULATION_RUN_ID", OleDbType.Integer).Value = Main_Class.Calculation_Run_ID;
//Main_Class.con.Open();
cmd.ExecuteNonQuery();
Main_Class.con.Close();
}
catch (OleDbException ex)
{
//get the error message if connection failed
MessageBox.Show("Error in connection ..." + ex.Message);
Main_Class.con.Close();
}
Well a quick look says you have an extra comma
This: [RA_INPUTS]=?, WHERE should be [RA_INPUTS]=? WHERE