如果是在同一项目中可以直接通过 类名.Connection 的方式来获得相关的连接,则要把该连接设为static,如 class MyClass { public static SqlConnection Connection = new SqlConnection(...); } 也可做成为属性形式,但属性也要为static的,这样可直接用: 在其它类中可:SqlDataAdapter da = new SqlDAtaAdapter(MyClass.Connectin);
我是楼主: 我的C#连接数据库是这么写的: using System.Data.SqlClient;namespace DataAccess { public class Sqlcon { private SqlConnection con; public SqlConnection Conn() {
不对
public static SqlConnection objConnection1(int intErrorCode)
{
SqlConnection Cn=new SqlConnection("server=zlp;database=CTKJ;uid=zlp;pwd=zlp");
try
{
Cn.Open();
return Cn;
}
catch(Exception e)
{
intErrorCode=1;
}
}
class MyClass
{
public static SqlConnection Connection = new SqlConnection(...);
}
也可做成为属性形式,但属性也要为static的,这样可直接用:
在其它类中可:SqlDataAdapter da = new SqlDAtaAdapter(MyClass.Connectin);
我的C#连接数据库是这么写的:
using System.Data.SqlClient;namespace DataAccess {
public class Sqlcon
{
private SqlConnection con;
public SqlConnection Conn()
{
//这个函数是公用函数,以后用到数据库就调用
string user = "zlp";
string pwd = "zlp";
string database = "CTKJ";
string dbserver = "zlp"; string strConn="";
strConn = "Data Source=" + dbserver + "; ";
strConn = strConn + "User Id=" + user + "; ";
strConn = strConn + "Password=" + pwd + "; ";
strConn = strConn + "Initial Catalog=" + database;
SqlConnection nwConn = new SqlConnection(strConn);
try
{
nwConn.Open(); //open connection;
}
catch(Exception e)
{
}
return nwConn;
}
}
}
在Asp.net 是这么调用的:
DataAccess.Sqlcon mycon;
mycon.Conn();
string myInsertQuery = "INSERT INTO logoinfo (学生用户名,学生用户密码) Values ('"+UserName.Text.Trim()+"', '"+UserPassWord.Text.Trim()+"')";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = mycon;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
为什么不行,快告诉我哪儿错了,好吗?
是长了一点.我改下:
我是楼主:
我的C#连接数据库是这么写的:
using System.Data.SqlClient;namespace DataAccess {
public class Sqlcon
{
private SqlConnection con;
public SqlConnection Conn()
{ SqlConnection nwConn = new SqlConnection("user id=zlp;password=zlp;database=CTKJ;SQLServer=MySQLSERVER");
try
{
nwConn.Open(); //open connection;
}
catch(Exception e)
{
}
return nwConn;
}
}
}
在Asp.net 是这么调用的:
DataAccess.Sqlcon mycon;
mycon.Conn();
string myInsertQuery = "INSERT INTO logoinfo (学生用户名,学生用户密码) Values ('"+UserName.Text.Trim()+"', '"+UserPassWord.Text.Trim()+"')";
SqlCommand myCommand = new SqlCommand(myInsertQuery);
myCommand.Connection = mycon;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
再看看,有什么错误吗?现在报的错误是没法与数据库连接,我也不知道怎么来测试C#连接数据库的程序,编译没错.
SqlCommand myCommand = new SqlCommand(myInsertQuery);
DataAccess.Sqlcon mycon = new DataAccess.Sqlcon();
myCommand.Connection = mycon.Conn();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
{
} public SqlConnection objConnection1(int intErrorCode)
{
SqlConnection Cn=new SqlConnection("server=zlp;database=CTKJ;uid=zlp;pwd=zlp");
try
{
Cn.Open();
}
catch(Exception e)
{
intErrorCode=1;
}
}
没有 return;
{
在资源管理器窗口-》引用--右击--》添加--》项目名称 //在不同的项目中
using 项目名称; //OK
}
ELSE
//不用我说了吧?