问题的提出:
现有类库文件 login.cs
现有类库文件 login.cs
using
System;
namespace conn
{
public class Login
{
// 在此类中定义一个静态的字段(属性),返回一个字符串
public static string Connection
{
get { return @" Server=database_servername;DataBase=Northwind;user id=sa;password=yourpassword; " ; }
}
// 注意 @不可以少!
}
}
namespace conn
{
public class Login
{
// 在此类中定义一个静态的字段(属性),返回一个字符串
public static string Connection
{
get { return @" Server=database_servername;DataBase=Northwind;user id=sa;password=yourpassword; " ; }
}
// 注意 @不可以少!
}
}
*******************************************************************
此时需要在DataReaderSql使用到类login中的字段Connection(下面代码第9行)
DataReaderSql.cs
******************************************************************
1
using
System;
2 using System.Data.SqlClient;
3
4
5 public class DataReaderSql
6 {
7 public static int Main( string [] args)
8 {
9 string source = Login.Connection ;
10 string select = " SELECT ContactName,CompanyName FROM Customers " ;
11
12 SqlConnection conn = new SqlConnection ( source ) ;
13
14 try
15 {
16 using ( conn )
17 {
18 conn.Open ( ) ;
19
20 SqlCommand cmd = new SqlCommand ( select , conn ) ;
21
22 using ( SqlDataReader aReader = cmd.ExecuteReader ( ) )
23 {
24 while ( aReader.Read ( ) )
25 Console.WriteLine ( " '{0}' from {1} " , aReader.GetString( 0 ) , aReader.GetString ( 1 ) ) ;
26
27 aReader.Close ( ) ;
28 }
29
30 conn.Close ( ) ;
31 }
32 }
33 catch ( Exception e )
34 {
35 Console.WriteLine ( e ) ;
36 Console.WriteLine ( ) ;
37 Console.WriteLine ( " Chances are your database does not have a user " ) ;
38 Console.WriteLine ( " called QSUser, or you do not have the NetSDK database installed. " ) ;
39 }
40
41 return 0 ;
42 }
43 }
44
45
2 using System.Data.SqlClient;
3
4
5 public class DataReaderSql
6 {
7 public static int Main( string [] args)
8 {
9 string source = Login.Connection ;
10 string select = " SELECT ContactName,CompanyName FROM Customers " ;
11
12 SqlConnection conn = new SqlConnection ( source ) ;
13
14 try
15 {
16 using ( conn )
17 {
18 conn.Open ( ) ;
19
20 SqlCommand cmd = new SqlCommand ( select , conn ) ;
21
22 using ( SqlDataReader aReader = cmd.ExecuteReader ( ) )
23 {
24 while ( aReader.Read ( ) )
25 Console.WriteLine ( " '{0}' from {1} " , aReader.GetString( 0 ) , aReader.GetString ( 1 ) ) ;
26
27 aReader.Close ( ) ;
28 }
29
30 conn.Close ( ) ;
31 }
32 }
33 catch ( Exception e )
34 {
35 Console.WriteLine ( e ) ;
36 Console.WriteLine ( ) ;
37 Console.WriteLine ( " Chances are your database does not have a user " ) ;
38 Console.WriteLine ( " called QSUser, or you do not have the NetSDK database installed. " ) ;
39 }
40
41 return 0 ;
42 }
43 }
44
45
**********************************************************
也就是说目前我们需要解决的问题是如何在编译的时候可以及时的让程序可以知道Login.Connection 在哪里。
那么我们应该怎么做呢?
在这里我们不依靠namespace我们使用动态链接库。
分2步:
I 使用命令csc /t:library login.cs 编译得到 login.dll
II 使用命令csc DataReaderSql.cs /r:login.dll 编译并指向login.dll动态链接库文件
得到DataReaderSql.exe
希望对刚开始学C#的并打算继续打好基础的人有所帮助!