.NET 数据库连接和查询

来源:互联网 发布:临沂知豆电动汽车 编辑:程序博客网 时间:2024/06/13 22:30

文件web.config下 

 <connectionStrings>    <add   connectionString="Data Source=.;Initial Catalog=Personal_MC;Integrated Security=True" providerName="System.Data.SqlClient"/>  </connectionStrings>

向数据库添加 

public static void AddAlbum(string Caption, bool IsPublic)    {        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);        string sql;        sql = "INSERT INTO [Albums] ([Caption],[IsPublic]) VALUES (@Caption, @IsPublic) ";        SqlCommand command = new SqlCommand(sql, connection);        command.Parameters.Add(new SqlParameter("@Caption", Caption));        command.Parameters.Add(new SqlParameter("@IsPublic", IsPublic));        connection.Open();        command.ExecuteNonQuery();    }

 从数据库提取数据

protected void Button1_Click(object sender, EventArgs e)    {        string connString = ConfigurationManager.ConnectionStrings["Personal"].ConnectionString;        int photoId = Convert.ToInt32(TextBox1.Text );        SqlConnection connection = new SqlConnection(connString);        string sql = "SELECT  BytesOriginal FROM Photos WHERE PhotoID = "+ @photoId ;        SqlCommand command = new SqlCommand(sql, connection);        command.Parameters.Add(new SqlParameter("@photoId", photoId));        connection.Open();        Stream stream = null;         object result = command.ExecuteScalar();   stream = new MemoryStream((byte[])result);            const int buffersize = 1024 * 16;            byte[] buffer = new byte[buffersize];            int count = stream.Read(buffer, 0, buffersize);            while (count > 0)            {                Response.OutputStream.Write(buffer, 0, count);                count = stream.Read(buffer, 0, buffersize);            //有颜色的为从数据库提取二进制图片代码   }

0 0
原创粉丝点击