I've some some light database programming in school, before, but I'm trying to learn best practices now that I'm writing more sophisticated applications. Writing to a MySQL database isn't hard, but I'm wondering what a best practice is for having distributed applications write to a remote database on Amazon EC2.
As of right now, I'll have a MySQL database hosted in the cloud that's able to receive incoming connections. I questioned this as by default, it only enabled the local host to connect to it.
Is there a more secure or professional way to write to a MySQL instance in the cloud than just doing some kind of DbConnect, hard coding my server's online host name, root username and password? I just don't want to make a production application that's not accessing the database in the best fashion.
Thanks! You guys are always awesome.
the most viable to date option for database work is to use something like entity framework
your model is the model, your database connection sits on its own and you can easily port the application to another database provider if need... I.E mysql to msSQL without really having to do much in the way of work.
Entity framework code first is the easiest i think to port over. Also for mysql you just need the mysql.net connector from the provider themselves, this works with entity framework.
also by working with models and using linq you further help reduce prodlems with SQL injection as you wont actually be writing or sending any SQL.
Given that, should you have a massive database, EF is a pain in the butt and is really slow and for this a simple database class would do, you can have a few functions like this:
private readonly MySqlConnection _conn = new MySqlConnection();
private MySqlCommand _myCommand = new MySqlCommand();
private readonly string _dbConn = ConfigurationManager.AppSettings["dbConn"];
public void Closedb()
{
try
{
_conn.Dispose();
_conn.Close();
}
catch (Exception ex)
{
}
}
public void UpdateDatabaseWithSql(string mysql)
{
Closedb();
_conn.ConnectionString = _dbConn;
_conn.Open();
_myCommand= new MySqlCommand(mysql,_conn);
_myCommand.ExecuteNonQuery();
Closedb();
}
a DB connection for mysql looks like this, in the web.config file:
<add name="MvcCustomContext"
connectionString="server=[ip];User Id=[user];password=[pass];Persist Security Info=True;database=[dbname]"
providerName="MySql.Data.MySqlClient" />
hope this helps
The best way is to have another application running on the server and listening a port on TCP to make the actions on the database. You can encrypt the message and decrypt on server application, having a safe username/password and data traveling.
Related
I have an application that I used to connect to a mySQL database. I have installed the MySQL.Data package and I use this code to build my connection:
services.AddScoped<System.Data.IDbConnection>((s) =>
{
IDbConnection conn = new MySqlConnection(Configuration.GetConnectionString("databasename"));
conn.Open();
return conn;
});
This works fine as I am able to read/write data from the database.
Now, I need to have the same application access a MS SQL database. The tables are all the same and the fields on each table are the same as well. I am having a hard time finding what I should change my code to (or what package I should include). When I remove the MySQL.Data package, the MySqlConnection function becomes invalid (as would be expected).
Any idea what package to include and what function to use to establish the connection?
Any assistance is greatly appreciated.
Thank you!
EDIT #1
I found an old stackoverflow post (I should have referenced it here but I closed the window) that talks about this very issue. The suggestion was to add
using System.Data.SqlClient;
and then change the assignment code to
IDbConnection conn = new SqlConnection(Configuration.GetConnectionString("databasename"));
I made these changes and now I get this error within the code:
Im at a loss as to how to resolve this. I verified that my project is in framework .NET core 3.1
Not sure about size of your project and detailed requirements but I would suggest to use libraries like:
Entity Framework - no SQL knowledge needed, can connect to any Db technology, almost no code changes required when switching between Db providers
or
Dapper - fast lightweight also supports multiple Db providers but you need to write correct SQL commands yourself specific for each Db technology you use
I'm totally new to Web Programming, and have been asked to produce a web form that will be hosted on the company Intranet Site. The form will be used to submit data to a back end database.
My problem is that the database has been developed using MS Access 2007. Whereas I would like to use ASP.NET MVC 3 I'm not sure I will be able to us MS Access for this as a back-end database. Most examples I seem to find all hook up to SQL Server (Data Context), which i understand is the best way to go about it.
My problem is that due to time restrictions, I wont be able to change this database over to SQL at present. There has been a lot of work done creating things such as Forms, Reports etc within the Access Database that I don't have time to replicate in .Net for now.
Can anyone give me some advice on which would be the best method for building a Intranet Data Entry form in the short term.
I will look to bring the entire project up to date when the time is available.
You should be able to simply add the Access connection string to the web.config file and use that DB instead.
<connectionStrings>
<add name="MyConn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|name_of_db.accdb;" providerName="System.Data.OleDb" />
</connectionStrings>
Model-View-Controller is a software design pattern, referring to separation of the interface and logic.
You can still use MVC with MS Access. You could use the OLEDBConnection class, however I would recommend you use an ORM such as NHibernate which supports Access connectivity (Tutorial outlined below).
At a later date you can simply map all of the NHibernate mappings to SQL Server and switch the connection string which will point at your new SQL Server database rather than MS Access.
Linking MS Access to NHibernate:
http://www.thoughtproject.com/Snippets/NHibernateWithAccess/
Connecting to MS Access via OLEDB:
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
// C#
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();
}
}
More info at MSDN.
I have three computer in a office and I have installed my C#-2005 Project on all three
computers. But Problem is that Boss wants Sql-server-2000 on One PC out of three and other
would share the same.
I don’t know how to share Sql-server-2000 between three PC?. How to do?.
Confusion:-
Thanks for your co-operation but here I have a confusion on majority people said to check
TCP/IP address and consider the Connection string as per main server from client PC.
Suppose I have financial project and there would be thousand of connection string in a
project. As per above I have to change thousand of connection string as per main pc.
Now think it is a one customer's need If I have ten cutomer having same offer than think How much time I have to waste on it?. I have to modify thousand of connection string ten time more?.
If it is true than it will take lots of time on installation to each customer.
I don’t know if it is only way?.
The Connection string I have utilized on my each winform is as below:
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Here suggested about Config File and same I don't know if some body give me idea about how to consider it with my C#2005 project than it will save my lots time.
When you connect to the database in your code, you'll a database connection string of some sort somewhere in there. Figure out the connection string for the Database server and set your code to point to that database server's connection info; I'd bet you currently you have it pointed at localhost
If you're using SQL Server you may need to enable remote connections on the database server.
added: you may need to modify firewall settings as well to allow SQL Server traffic (thanks Jared)
.
Edit: For putting the configuration string into a central location.
Your posted code
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Change to
Assuming your application has a App.Config file then you'd add an entry in there like
<add key="DBConnectionString" value="server=.;initial catalog=maa;uid=mah;pwd=mah"/>
And change your C# code to be like
string connstr = ConfigurationManager.AppSettings["DBConnectionString"];
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Putting the ConfigManager call into a class might be a good idea if you have a lot of settings to retrieve and/or believe the configuration storage methodology might change down the road. Going with the above example is WAY better than having the string literal scattered throughout your code.
Enable theTCP/IP connection in SQL Server. So that you can connect remotely from any pc within the network
check here
If your problem is that you embedded your connection string in the code, then you are going to have to do some refactoring. These would be the general steps, you will have to tailor them a bit to your situation.
Add your connection string to the app.config file.
Create a static/shared method that will read the connection string from the
config file.
Do a find and replace in your solution to replace all
of the hard coded connection strings in your code with the (class
and) name of the method that gets the connection string.
This is probably going to be easier than rewriting all of your data calls to use something like enterprise library or EF.
You will need to do as the others suggested, such as changing the connection string and enabling TCP/IP within SQL Server, but you will also likely need to configure your firewall to allow requests to SQL Server (default port of 1433) through.
I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net
Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe
I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.
Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.
I believe this question is about the "Local Database" item template in Visual Studio:
What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET
Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/
For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.
I have been working in a business writing advanced software apps, and obviously im provided with access to our SQL server and all the connection strings needed.This is fine for my job now - but what if i wanted to do this for a new (very small) business... If i wanted to purchase a small database server and set up a piece of software that talks to the databases on this server, how would i go about a) Talking and connecting to the server in code (c#) and b)What would i need regarding things like internet/phone connections etc to make this possible.
Edit: the reason it would need a server is because it would need to be accessed from 2 or 3 different computers in different locations?
Actually there are quite a few ways to create a database connection, but I would say one of the easiest ways is to utilize the methods and classes found in System.Data.SQLClient. A basic connection would look something like the following:
using System.Data.SQLClient;
namespace YourNamespace
{
public class DatabaseConnect
{
public DataType getData()
{
DataType dataObj = new DataType();
SqlConnection testConn = new SqlConnection("connection string here");
SqlCommand testCommand = new SqlCommand("select * from dataTable", testConn);
testConn.Open()
using (SqlDataReader reader = testCommand.ExecuteReader())
{
while (reader.Read())
{
//Get data from reader and set into DataType object
}
}
return dataObj;
}
}
}
Keep in mind, this is a very, very simple version of a connection for reading data, but it should give you an idea of what you need to do. Make sure to use a "using" or "try/catch" statement to ensure that the connection is closed and resources are freed after each use (whether it successfully gets data or not).
As for your other question about what equipment you may require. In the beginning I would suggest just creating the database on your local machine and running tests from there. Once you are confident with trading data back and forth, feel free to move the database to another box or an online server. Any internet connection type should suffice, though I can't vouch for dial-up, haven't used it in years.
One final note, if you do happen to decide to move to an online server system, make sure that the service you use allows for outside connections. Certain services use shared server systems, and force users to use their internal database interfaces to manage and write to the database.
--- EDIT ---
As for the server system itself, build up a separate box on your local network that you can see, and load up the database software of your choice. Since you are using C#, it would probably be easiest to go with Microsoft SQL Server 2005 / 2008. The installation is rather straightforward, and it will prompt you to automatically create your first database while installing.
After installation it will be up to you to add in the tables, stored procedures, custom functions, etc... Once your base structure is created, go ahead and use the above code to make some simple connections. Since you are familiar with the above practices then I'm sure you know that all you really need to do is target the server machine and database in the connection string to be on your way.
In case your application is small (by small I mean the usage of resources like CPU and memory) then your SQL Server can reside on the same box.
Else you need to have a separate server box for your database and connect to that from your application. In this case, preferably your database box and application box would be on the local area network.
Check this link for having a connection to SQL Server from C# code - http://www.codeproject.com/KB/database/sql_in_csharp.aspx
cheers
You should probably expose your database with an xml web services layer, so that your architecture will be scalable. The general idea is host your sql server and webservices, using Native SQL Server XML Web Services you can make this available to your remote clients. When in your clients you simply add a service reference in Visual Studio and your data will now be available in your client app.
Hope this helps some.
Cheers
You may find the connectionstrings website useful - worth bookmarking.