I'm trying to teach myself c#, and have found various examples on connecting to a MSSQL database. What I've done seems to be the simplest way to do it, but still seems overly complicated.
Is there a better way?
here's my code:
static void dbcon()
{
List<int> familyID = new List<int>();
String connString = "Server=[myServer]\\[myInstance];Database=[dbName];User Id=[userID};Password=[password];";
using (var sqlconn = new SqlConnection(connString))
{
using (var cmd = sqlconn.CreateCommand())
{
try
{
sqlconn.Open();
cmd.CommandText = "SELECT id FROM family";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
familyID.Add(Convert.ToInt32(reader["id"].ToString()));
}
}
foreach (int tempy in familyID)
{
Console.WriteLine("id: " + tempy);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
This is fine for an app that only runs one sql statement, but you wouldn't want to use all that code every time you wanted new data.
What you want to do is separate the code that creates the connection, from the code that gets and runs the sql, from the code that deals with the results.
This way, the connection code (and possibly the data display code) can be written once and called each time you want to execute different sql, and you only have to concentrate on how to write the code that gets the data you want.
hth
Details: First of all welcome to Stackoverflow. Just a few tips below
Having your connection string hard coded like that is bad practice. You should ALWAYS have it in your App.config (or Web.config if it is a web application). The reason is because if you have it hard coded and your boss ask you to change the Applications Database connection string you will need to recompile the entire application. If you have it in a App.config file you just need to change it (open it up with notepad) and save it.
Example on how to add it to the app.config
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB;
Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then to access it in your code (You will need to add a reference to System.Configuration as well as add using System.Configuration;)
string connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
In regards to your other code I would change your exception catching to include the Sql Exception first and then fall back to any other exceptions.
catch (SqlException ex)
{
// Handle the Sql Exception code
}
catch (Exception ex)
{
// Handle the Normal Exception code
}
The example contained in the docs for SqlConnectionStringBuilder is quite easy to follow and understand as an alternative way.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
Edit:
Actually, the example I copied above shows you how the SqlConnectionStringBuilder class handles an "...invalid value in a safe manner". Whoops. At least it gives you an idea of how it works.
For more info on the various methods of obtaining, storing and constructing your connection string within ADO.NET, look at the MSDN documentation on Connection Strings
Related
I want to create a connection for my UWP and database. I want the uwp to send a value to the database.
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1; uid = root;" + "pwd=root;database=test";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
}
Is this the correct way to write the connection ? and where do I write this part of the coding at ?
enter image description here
Main page or any of my other page ? (scenario 1-3)
Your content looks right, I would try to use 'localhost' rather than ip.
var myConnection = new MySqlConnection();
myConnection.ConnectionString = "database=test;server=localhost;uid=root;pwd=root";
myConnection.Open();
More info see: https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm
I would also check here to see if you are providing enough info, which you are. https://www.connectionstrings.com/mysql/
In terms of connecting to the database, it depends. What type of application is this? Typically, database connections are made during the start of the application. If you are using Entity Framework, you'll want your Database Context to manage the connection (which is an entirely different topic).
Most people seem to have the opposite problem, but the solution is "grant access on the DB." I want to restrict access for one of two connections to the database (LocalDB). I'm afraid the answer is "create a database user and use that to connect." This is for testing only and I don't want to provision a user. Is there any way to enforce a readonly connection with LocalDB, say, through a connection string? I doubt it, but I thought I'd ask. Here's my current connection string:
<add name="readonlyConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Database=test;Trusted_Connection=True; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
The implementation is much more complicated but basically uses the System.Data.Entity.DbContext class, if that helps.
Short answer: No.
Longer answer:
You can find all of the options available for connection strings here; in short, the permissions assigned to a connection are not a concern of the ConnectionString class; they're a concern of the database.
People have tried to do this with Entity Framework and it has only resulted in a series of hacks that are more work than just creating the darn user in the first place.
Here's what you do (in a context that's not readonly):
using (var connection = (db as DbContext).Database.Connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = "sp_executesql";
command.CommandType = CommandType.StoredProcedure;
var param = command.CreateParameter();
param.ParameterName = "#statement";
param.Value = #"
CREATE LOGIN readonlyLogin WITH PASSWORD='testpassword'
CREATE USER readonlyUser FROM LOGIN readonlyLogin
EXEC sp_addrolemember 'db_datareader', 'readonlyUser';
";
command.Parameters.Add(param);
connection.Open();
try {
command.ExecuteNonQuery();
} catch (SqlException ex) { // user already exists
if (ex.Errors[0].Number.Equals(15025)) { } else throw ex;
}
}
}
And then, in your connection strings for your test project:
<add name="readonlyConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Database=test;Trusted_Connection=False;User Id=readonlyLogin;Password=testpassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
In a web app, I am using SQL server. However, when I try to store some bulk amount of data, it misses some of the records and does not insert them into the database. I want to know whether there is any commit statement or synchronization for the database? Data is being sent object by object using an ajax call.
Here is my code:
try
{
int surah = Convert.ToInt32(Request["surah"]);
string verse = Request["data"];
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True";
System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);
string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,"+surah+",'"+verse+"')";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception e){
System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\ExceptionFile.txt", true);
file.WriteLine("exception details : "+e.ToString());
file.Close();
}
As you understand, the records cannot get lost in the way. Either the INSERT statement would execute, or you would get an exception. Since neither is happening, I believe that you loose something in the request generating mechanism.
I would strongly suggest to put some logging message on each request. You will probably find out that your requests are less than you thought. This could be for a number of reasons, but since I don't know the exact mechanism calling the server side code, I cannot have an opinion.
Hope I helped!
I'm maintain an app that uses an access database, I would like to use something smarter than formatting sql statements on the fly, so out of my limited options I decided to use a strongly Data Set, but I need the option to change the data source its using on the fly, as the user can change which database its pointing at, the db are same as far a schema goes, the only difference is a data, is there a good way of doing this? I basically need to ignore whats in the config settings, and use the path the user picks.
You can change the connection string by changing the data source connection string that points to the datafile in this example
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
#"Data source= C:\Documents and Settings\username\" +
#"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
I'd like to provide a command line interface to my db that allows the user to enter MULTIPLE database commands or queries (separated by line breaks in the textarea)
For each line, if its a query must return the results and if its a command, whether or not it was successful - thus allowing the user to paste a script into the text area and click 'GO' to have the batch executed.
I have been using a DataContext to interface with my database in the application but havent a CLUE where to start. Any assistance would be greatly appreciated
Think about the security issues that you are bringing into your Website.
Think again about the security. How can a clever user (more clever as you/me) hack into the database using this page. Maybe/probably using some misformed SQL, that you do not think about in this stage.
Use a direct SqlConnection and SqlCommand when the database you are using is SQL server. Use the oracle or other provider counterparts when you need to use these. A SqlCommand can return more as 1 result, this is handy in the case of multiple commands in one query. See the NextResult method for more information.
As the previous answer points out, please don't do this if it's a publicly accessible site!
If you must do it, the following code is close to what you're after - with a bit of modification you'll get exactly what you want.
public static bool ExecuteSql(string sqlScript)
{
bool success = true;
using (SqlConnection cn = new SqlConnection([YourConnectionString]))
{
SqlCommand cmd = null;
try
{
cn.Open();
string[] commands = sqlScript.Split(new string[] { "GO\r\n", "GO ", "GO\t" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string c in commands)
{
cmd = new SqlCommand(c, cn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
success = false;
throw new Exception("Failed to execute sql.", ex);
}
finally
{
cn.Close();
}
return success;
}
}