FileInputStream fis = new FileInputStream("hashmap.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
extras = (HashMap) ois.readObject();
ois.close();
fis.close();
我的visitorcompany班:
public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(@CompanyName, @Location1)", conn);
cmd.Parameters.AddWithValue("@Companyname", companyname);
cmd.Parameters.AddWithValue("@Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
我正在尝试一次搜索一行,以检查sql表是否具有相同的公司名称。如果已经存在公司名称,则该程序将不执行任何操作。如果这是新的公司名称,则程序会将公司名称添加到sql表中。但是,添加新公司名称时,该程序将添加多次。有人可以帮我重新编辑程序,使其仅添加一个新的公司名称。非常感谢。
答案 0 :(得分:0)
不要使用companyname
作为插入命令的参数,因为它在for循环中保持不变。请改用result.Tables["details"].Rows[i]["Companyname"].ToString()
:
...
cmd.Parameters.AddWithValue("@Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
答案 1 :(得分:0)
检查值是否存在,如果没有,请然后添加。
代码中的一个简单更改:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(@CompanyName, @Location1)", conn);
cmd.Parameters.AddWithValue("@Companyname", companyname);
cmd.Parameters.AddWithValue("@Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
当然,您可以检查值是否以更有效的方式存在,但这至少应该可以解决您的特定问题。
答案 2 :(得分:0)
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}