I am new to asp.net. How do I write the codes for MySQl database using asp.net?
Currently, I found this and I think it is not enough to connect the database.
SqlConnection con = null
SqlCommand cmd = null
SqlDataReader rdr
From what i know they uses public class as well which is similar to java. However, I am not too sure about how it goes.
I would need the codes to define the variables and together with the command statement. Replying to me is much appreciated. Thank you.
Having a look at google gives the following post on developerfusion:
http://www.developerfusion.com/code/4596/how-to-access-a-mysql-database-with-net/
Related
VS Express 2012, SQL Server Express 2012, Win 8.1
Hello,
I have a (very) simple WCF hosted as a web service on IIS. I also have a SQL Server instance (with 1 table) installed on the same machine.
I need a step-by-step guide on how to connect to SQL from the WCF (VB) and retrieve a single record from the table (ie: "SELECT LAST NAME FROM MYTABLE WHERE PK = 1;"). That's it. I don't need a 1,200 page manual -- which is all Google keeps throwing at me.
Anyone know of a quick, clean resource?
Thanks,
Jason
The main classes that are involved are SqlConnection and SqlCommand. The documentation of the classes contains some samples on how to use them. To get you started, here is a small sample:
Dim connStr = "Data Source=SQLServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=SSPI"
Using conn As New SqlConnection(connStr)
conn.Open()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT LAST_NAME FROM MYTABLE WHERE PK = #pk"
cmd.Parameters.AddWithValue("#pk", 1)
Dim result = cmd.ExecuteScalar()
If Typeof result Is DbNull Then
' Handle null value
Else
' Otherwise
End If
End Using
End Using
This sample assumes that you want to retrieve a single cell as in your statement. If you want to retrieve tabular data, have a look a the SqlDataReader or SqlDataAdapter class.
Please note that - especially in server applications - it is important to dispose of the created instances properly.
There is no difference on using ADO.NET in a WCF service or in a normal application from the point of view of the classes required.
The first thing needed is a connection string that allows your SqlConnection object to find the host and the database that you want to use. Here examples on connection strings
Then you usually need a SqlCommand that encapsulates the SQL text and parameters needed to retrieve the data (Here you setup your SELECT statement and conditions)
Finally you need a SqlDataReader that get the result of the command execution and allows you to loop over the results.
Here a sample that could get you started.
Keep in mind that this is just a minimal todo-list and there are numerous other ways to work with data. Basic objects like SqlDataAdapter, Dataset, DataTable present different ways to load data from a database and use that data. Then on top of these there are technologies like Linq To Sql and Object Relational Mapper tools that abstract the data access and offer high level functionality on top of data.
That's probably the reason you get so much informations on data access technologies
I`m creating a website using asp.net, and I need to use a local SQL server (using Microsoft SQL server). And I have created database and tables in it using the MS SQL Server Management Studio.
Now I successfully connect to the database and do some simple add/query using the following commands:
string connectionString = "data source=ABCD\\SQLEXPRESS;initial catalog=PMD;Trusted_Connection=yes;";
string sqlQuery = "INSERT INTO PMD (username, userID, userAddress)";
sqlQuery += " VALUES (#user, id, add)";
SqlConnection dataConnection = new SqlConnection(connectionString);
SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection);
dataCommand.Parameters.AddWithValue("user", USER.Value);
dataCommand.Parameters.AddWithValue("id", ID.Value);
dataCommand.Parameters.AddWithValue("add", ADDRESS.Text);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
The command above can add one column to the table, with values stated.
The query is done in a similar way. Compared with Linq, this is not very concise.
So I was wondering how can I change the code so I can use Linq.
The biggest question for me now is how to connect to the base. I already know all the syntax of Linq.
eg: var query=from c in db.username where c.Contain(“Micheal”) select c (or maybe db.PMD.username)
How can I get the db to link with ABCD/SQLEXPRESS, table PMD?
First you need an Object/Relational Mapper (O/RM). You can't just put LINQ on top of your old ADO.NET code.
Microsoft provides two: Linq2SQL and Entity Framework.
Linq2SQL has been discontinued. If I had to choose between the two, I'd go with Entity Framework.
Here you can find an introduction: http://www.asp.net/entity-framework
For example, install Entity Framework, then connect to sql server with entity framework
I'm getting an error when running the following code thru an ASP/ C# .NET page:
SELECT 1 FROM [database].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='example_table'
The code runs perfectly when I run it in the sql management studio query window.
It's also only broken for 1 specific server - when I run on a different server with a different connection string, it works fine.
I've scoured the internet, and all I can seem to find as an answer is that there are issues with case sensitivity, but I'm using all uppercase, and the table in question is using SQL_Latin1_General_CP1_CI_AS collation anyway.
Based on all this, I'm pretty sure it's some kind of permissions issue, but I'm not really sure where to look.
The error I'm getting:
Invalid object name 'database.INFORMATION_SCHEMA.TABLES'.
The connection string:
<add name="connectionName" connectionString="Data Source=servername; Initial Catalog=master; User ID=user; Password=pw" providerName="System.Data.SqlClient"/>
UPDATE:
Some more information: I had adapted this code from some older VB stuff that basically does the same thing. The VB code runs the same exact query on the same servers and databases, but it works.
The VB code:
Dim connStr As String = ConfigurationManager.ConnectionStrings("connectionName").ConnectionString
Dim objConnection As SqlConnection = New SqlConnection(connStr)
Dim objCommand As SqlCommand = New SqlCommand("SELECT 1 FROM [database].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='example_table'", objConnection)
objCommand.CommandType = CommandType.Text
objConnection.Open()
The C# and VB code both use the exact same connection string from web.config, so I suppose that leads me to doubt that it would be a permissions issue. Still no clue what the problem is though.
It's a copy paste issue in your case I hope, change the [database] with your DB name.
After a bunch more debugging, I was able to determine that the code was actually running on the wrong server. So, not really any way to find the bug based on what I'd posted, but I think Tony was on the right track based on the back-and-forth.
I've created an application using ASP.NET with Access DB, now I found somee.com who support only SQL Server DBs, so Now I must convert my Access DB to SQL Server DB.
Is there any tool who can do the trick ?
This is some code I'm using in my web application :
Public Shared Function conecter() As OleDbConnection
Dim MyConnexion As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & System.AppDomain.CurrentDomain.BaseDirectory & "/Learning.mdb")
MyConnexion.Open()
Return MyConnexion
End Function
Public Shared Function lecture(ByVal requete As String) As OleDbDataReader
Dim Mycommand As OleDbCommand = conecter().CreateCommand()
Mycommand.CommandText = requete
Dim myReader As OleDbDataReader = Mycommand.ExecuteReader()
Return myReader
End Function
In this case, If I convert my database I must change the OleDbConnexion and other things or I can just leave them like that ?
Your connection string will need to change. Connectionstrings.com is a good resource for this if you're having problems figuring out how to set up a SQL connection string.
For upward migration, take a look at the Access Upsize Wizard - this link is for 2002 since I'm not sure what access version you have.
If for some reason you do not have sufficient access to your SQL database to handle an upsize directly, you'll likely need to just generate the database schema and knock out a bit of migration code.
If you have access 2007, there is inbuilt option convert access database to SQL other wise there are somany tools available for free.
bullzip free converter
Try MUST
It was developed by a colleague of mine (we designed the website: www.upsizing.co.uk).
It does a fair bit more than the MS tools.
I'm designing a web service in ASP.NET and VS2008, and am using typed datasets for retrieving table data. These work well and establish their own connections through their associated TableAdapter objects. Edit: I'm using VB, BTW!
I am now attempting to run a custom SQL string using a DataAdapter and a Command object, however I need to reference a Connection object in order for the Command to work. What is the best way to handle this? Should I:
a) Create a global connection object using Global.asax, retrieving the connection string from web.config? (I've been trying that one already, with not much success)
b) Create a class-level connection object using the InitialiseComponent method, also retrieving the ConnectionString from web.config?
c) Retrieve a Connection from one of the TableAdapters that I've already created in my typed DataSets?
d) Something else I haven't thought of yet?
BTW I've been finding it very difficult to extract a ConnectionString from web.config, so any help with that would be appreciated also!
I'm not entirely inexperienced with ASP.NET, but my last big project used VS2003, and I want to make sure that I'm using the current tools correctly.
To extract the connection string, use
WebConfigurationManager.ConnectionStrings["name"].ConnectionString
It's best to open and close the connections as close as possible to their use. ADO.NET will do connection pooling so that this won't be expensive:
var connectionString =
WebConfigurationManager.ConnectionStrings["name"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("query", conn))
{
conn.Open();
// Use the command
}
}
For Connection and data access problems I will advise you to go with some kind of Data Helpers like Microsoft Data Access Application Block
Here you can find small tutorial about how to use it.
For getting connectionstring from web.config use folowing methods
public static string GetConnectionString( string strConstringKey )
{
return ConfigurationManager.ConnectionStrings[strConstringKey];
}
public static bool GetConnectionString(string strConstringKey, ref string strConstring)
{
return (strConstring = ConfigurationManager.ConnectionStrings[strConstringKey] ) == null ? false : true ;
}