本文實(shí)例講述了C#簡(jiǎn)單連接sql數(shù)據(jù)庫(kù)的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
using System; using System.Collections.Generic; using System.Text; //數(shù)據(jù)庫(kù)操作對(duì)象庫(kù) using System.Data; using System.Data.SqlClient; using worddic; namespace testDB { class Program { static void Main( string [] args) { //char[] array = new char[2] ; string [] a = new string [2]; FileOp words = new FileOp(); words.openfile( "worddic.txt" ); words.getwords( ref a); /* Console.WriteLine("請(qǐng)輸入Data Source:"); string data_source = Console.ReadLine(); Console.WriteLine("請(qǐng)輸入Initial Catalog:"); string initial_catalog = Console.ReadLine(); Console.WriteLine("請(qǐng)輸入user id:"); string user_id = Console.ReadLine(); Console.WriteLine("請(qǐng)輸入pass word:"); string pword = Console.ReadLine(); //連接字符串 string strConn ="Data Source="+data_source+";Initial Catalog="+initial_catalog+";User ID="+user_id+";Password="+pword+"";//YourPwd替換為你設(shè)置的sa賬戶密碼 */ string strConn = "Data Source=HYPER-V-WIN2003\\SQLSRV2005;Initial Catalog=Mytest;User ID=sa;Password=sa" ; SqlConnection conn = null ; SqlCommand sqlCmd = null ; try { //創(chuàng)建connection對(duì)象 conn = new SqlConnection(strConn); //打開數(shù)據(jù)庫(kù)連接 conn.Open(); //創(chuàng)建Transac Sql命令對(duì)象 sqlCmd = conn.CreateCommand(); //創(chuàng)建建表語句 //sqlCmd.CommandText = "create table wordlist(wrongwords varchar(30),rightwords varchar(30),sign char(20),)"; //sqlCmd.ExecuteScalar(); while (a[0] != null ) { sqlCmd.CommandText = "insert into wordlist(wrongwords,rightwords,sign) values('" + a[0] + "','" + a[1] + "',1 )" ; sqlCmd.ExecuteScalar(); a[0] = null ; a[1] = null ; words.getwords( ref a); } words.fileclose(); Console.WriteLine(); //打印所有記錄 } catch (SqlException e) { Console.WriteLine(e.Message); } finally { conn.Close(); } Console.WriteLine( "程序結(jié)束,按任意鍵退出" ); Console.ReadKey(); } } } |
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。