asp.net sql select语句问题

我有一张表(table1)有3个字段(id,brand,model)
还有一张表(table2)有3个字段(id,color,price)
我页面中放了两个Dropdownlist控件(Dropband,Dropmodel分别与数据中的brand,model绑定了,浏览的时候都能点出来了)
还放了两个Textbox控件(Txtcolor,Txtprice)
当然还有一个Button(BtnSave)
我现在是想点完保存按钮(BtnSave)可以把table1中对应(band,model)的id,Txtcolor,Txtprice这三个值放到table2中。
(也就说要先查询table1中满足两个Dropdownlist控件条件产生的id,连同两个Textbox上的内容放到数据库表table2中)
(注,数据库名为dataphone)
请高手写出完整的代码:

//保存按钮事件函数.
protected void BtnSave_Click(object sender, System.EventArgs e)
{
string strSqlGetID = "select ID from table where brand='" + Dropband.SelectedItem.Text.ToCharArray() + "' and model='" + Dropmodel.SelectedItem.Text.ToString() + "'";
var strID = Convert.ToString(ExecuteScalar(strSqlGetID));
//如果没有查询到ID则进行新增操作,查到了就进行更新操作
if (string.IsNullOrEmpty(strID)) {
string strSqlInsert = "insert into table2 (id,color,price) values (" + strID + "," + Txtcolor.Text.Trim() + "," + Txtprice.Text.Trim() + ",)";
if (ExecuteScalar(strSqlInsert) > 0) {
Response.Write("<script>alert('新增记录成功!')</script>");
}
}
else {
string strSqlUpdate = "update table2 set color='" + Txtcolor.Text.Trim() + "' price='" + Txtprice.Text.Trim() + "' where id =" + strID;
if (ExecuteScalar(strSqlUpdate) > 0) {
Response.Write("<script>alert('更新记录成功!')</script>");
}
}
}

//从数据库取出结果集第一行第一列数据.
public static object ExecuteScalar(string SqlStr)
{
//声明一个执行数据库语句的变量
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand();
try {
Command.CommandText = SqlStr;
//获取数据库连接
Command.Connection = new SqlClient.SqlConnection(connectionString);
//打开数据库连接
if ((Command.Connection.State == ConnectionState.Closed)) {
Command.Connection.Open();
}
//执行数据库命令
Command.CommandType = CommandType.Text;
object obj = null;
System.Data.SqlClient.SqlDataReader r = Command.ExecuteReader();
while (r.Read()) {
obj = r.GetValue(0);
}
return obj;
}
catch (Exception ex) {
throw ex;
}
finally {
//关闭连接
if ((Command.Connection.State != ConnectionState.Closed)) {
Command.Connection.Close();
}
//注销变量
Command.Dispose();
}
return null;
}

//执行数据库操作,返回操作成功数
public static int ExecuteSql(string SqlStr)
{
//声明一个执行数据库语句的变量
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand();
try {
Command.CommandText = SqlStr;
//获取数据库连接
Command.Connection = new SqlClient.SqlConnection(connectionString);
//打开数据库连接
if ((Command.Connection.State == ConnectionState.Closed)) {
Command.Connection.Open();
}
//执行数据库命令
Command.CommandType = CommandType.Text;
return Command.ExecuteNonQuery();
}
catch (Exception ex) {
throw ex;
}
finally {
//关闭连接
if ((Command.Connection.State != ConnectionState.Closed)) {
Command.Connection.Close();
}
//注销变量
Command.Dispose();
}
return 0;
}

//我搭环境花了好些时间.应该是没问题.楼主试试吧.
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-01-29
先占楼,楼主在线等.马上好.
====================
以下代码已测试通过.楼主只需要:
1.新建一个aspx文件,把原来的全删除,把下面的代码全复制过去.
2.改改数据库连接字符串

就可以使用:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

//数据库连接字符串,楼主这里应该改为自己的
private string connectionString = @"data source=.\sql2000;database=shiyu;uid=sa;pwd=sa;";

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//显示两个Dropdown中的数据
DataSet ds = new DataSet();

new SqlDataAdapter("select distinct brand from table1", connectionString).Fill(ds, "brand");
new SqlDataAdapter("select distinct model from table1", connectionString).Fill(ds, "model");

this.Dropband.DataSource = ds.Tables["brand"];
this.Dropmodel.DataSource = ds.Tables["model"];

this.DataBind();
}

}

//保存
protected void BtnSave_Click(object sender, EventArgs e)
{
//保存数据

//1.先取table1中的id
SqlCommand cmd = new SqlCommand("select top 1 [id] from table1 where brand=@brand and model=@model");
cmd.Parameters.AddWithValue("@brand", Dropband.SelectedValue);
cmd.Parameters.AddWithValue("@model", Dropmodel.SelectedValue);

cmd.Connection = new SqlConnection(connectionString);

cmd.Connection.Open();

object result = cmd.ExecuteScalar();

cmd.Connection.Close();

if (result == null)
{
LblResult.Text = "没有找到对应的brand和model的id";
return;
}

//2.insert到table2中

int id = (int)result;//id是int数据类型,楼主可以改为自己的类型

cmd.CommandText = "insert into table2 values (@id,@color,@price)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@color", Txtcolor.Text);
cmd.Parameters.AddWithValue("@price", Txtprice.Text);

try
{
cmd.Connection.Open();

cmd.ExecuteNonQuery();

this.LblResult.Text = "操作完毕";
}
catch (Exception ex)
{
this.LblResult.Text = "操作出现错误:" + ex.Message;
}
finally
{
cmd.Connection.Close();
}

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Brand:<asp:DropDownList ID="Dropband" runat="server" DataTextField="brand" DataValueField="brand">
</asp:DropDownList>
Model:<asp:DropDownList ID="Dropmodel" runat="server" DataTextField="model" DataValueField="model">
</asp:DropDownList>
Color:<asp:TextBox ID="Txtcolor" runat="server"></asp:TextBox>
Price:<asp:TextBox ID="Txtprice" runat="server"></asp:TextBox>
<asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSave_Click" />
<asp:Label ID="LblResult" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
第2个回答  2010-01-29
朋友按照你的方法我做了一次,这是代码:
public const String SQLCONNECTION = "Data Source=.\\sqlexpress;Initial Catalog=dataphone;User ID=sa;Password=1";
protected void Button1_Click(object sender, EventArgs e)
{
//SQLCONNECTION为连接字符串
SqlConnection connection = new SqlConnection(SQLCONNECTION);
String cmdText = "SELECT id FROM table1 WHERE brand=@brand AND model=@model";
SqlCommand cmd = new SqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@brand", this.DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@model", this.DropDownList2.SelectedItem.Text);
int id = 0;
try
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//判断取出来的是不是空
if (reader["id"] != DBNull.Value)
{
id = Convert.ToInt32(reader["id"]);
}
}
reader.Close();
reader.Dispose();
}
finally
{
connection.Close();
connection.Dispose();
cmd.Dispose();
}
//判断ID是不是等于零,不等于零时才能插入
if (id != 0)
{
//这个@是因为多行,我就不都整一行了,所以加了个@
String cmdText2 = @"INSERT INTO table2
(
id,
color,
price
)
VALUES
(
@id,
@color,
@price
)";
SqlConnection connection1 = new SqlConnection(SQLCONNECTION);
cmd.CommandText = cmdText2;
cmd.Connection = connection1;
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@color", this.Txtcolor.Text);
cmd.Parameters.AddWithValue("@price", this.Txtprice.Text);
try
{
connection1.Open();
cmd.ExecuteNonQuery();
//这里我就不用定义变量接收反回的行数了,你要用的时候自己加一下就可以了
}
finally
{
connection1.Close();
connection1.Dispose();
cmd.Dispose();
}

}
}
}
}
///////////////////////////////////////////
这是数据库代码:
CREATE DATABASE dataphone
GO
USE dataphone
CREATE TABLE table1
(
id INT IDENTITY(1,1) PRIMARY KEY,
brand NVARCHAR(20) NOT NULL,
model NVARCHAR(20) NOT NULL
)
GO
CREATE TABLE table2
(
id INT,
color NVARCHAR(20) NOT NULL,
price NUMERIC(10,2)
)
GO
希望对您有用,呵呵
第3个回答  2010-01-31
//查询出要插入新表table2的所有符合条件的id
string strSql1 = "select t.id from table1 t where t.brand='"+Dropband.SeletedItem.Text.Trim()+"' and t.model='"+Dropmodel.Selected.Text.Trim()+"'";

//用来存放插入语句
ArrayList strList = new ArrayList();
DataTable dt = new DataTable();
dt = oracleDB.GetTable(strSql1 );
if(dt.Rows.Count > 0)
{
for(int i = 0; i < dt.Rows.Count; ++ i)
{
string strSql2 = "insert into table2 t values('"+dt.Rows[i] ["id"]+"','"+Txtcolor.Text.Trim()+"','"+Txtprice.Text.Trim()+"')";
//将符合条件的插入语句放入strList中
strList.Add(strSql2);
}
}
//批量插入数据库
oracle.RunSqlArr(strList);

class oracleDB
{
DataTable GetTable(string strSql )
{
//根据sql语句得到DataTable
}

//实现单记录插入
protected void RunSql(string str)
{
//此处实现单记录插入相信你一定没问题
}

//实现批量插入
protected void RunSqlArr(ArrayList strList)
{
for(int i = 0; i < strList.Count; ++ i)
{
RunSql(strList[i].ToString());
}
}

}

注:对不起,因为没开发环境数据库连接的那部分我就不列出来了,你要的操作按照我上面写的实现没问题
第4个回答  2010-01-30
写个事务吧!先把符合dropdownlist的id查询出来,再写个insert语句把两个textbox的值和ID一同插入到第二个表中
相似回答