Before writing code, you must:
1. Introduce the assembly System. Data. dll in C: Program FilesUnityEditorDataMonolibmonounity (My unity is installed on the C drive by default ).
2. Copy the System. Data. dll file to the Current Unity project file, that is, under the Assets folder.
Although it can be run in unity, it still cannot be connected after it is published as web or exe, which requires three other dll files I18N. dll, I18N. west. dll, I18N. CJK. dll, these three files and System. data. the dll is in the same directory. To put the four dll files together in the Assets file and publish them, you can connect to the database.
Public class ConnectionSqlserver: MonoBehaviour
{
Void Start ()
{
// Connection string
SqlConnection connstr = new SqlConnection ("Data Source = ..; Initial Catalog = Exam; uid = sa; pwd = 123 ");
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = connstr;
Cmd. CommandType = System. Data. CommandType. Text;
// Set the SQL connection statement
Cmd. CommandText = "select * from Users ";
SqlDataAdapter sda = new SqlDataAdapter (cmd );
Sda. SelectCommand. Connection. Open ();
String strtemp = sda. SelectCommand. ExecuteScalar (). ToString ();
Sda. SelectCommand. Connection. Close ();
Print ("database connected! "+ Strtemp );
}
}