1

我正在使用 MVC4 和 Visual Basic 来制作 Web 系统。但是当我必须将数据保存在我的表和关系中时,我需要保存在很多表中。所以,我这样做:

conn.Open()
Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario)  VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn)
guardador_datos2.ExecuteNonQuery()
conn.Close()

conn.Open()
Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn)
guardador_datos3.ExecuteNonQuery()
conn.Close()

conn.Open()
Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn)
guardador_datos4.ExecuteNonQuery()
conn.Close()

我打开和关闭SqlConnection conn了很多次(例如,我在这里只放了三个,但实际上有 9conn.OpenClose)。

难道没有更好的方法来做到这一点吗?就像只打开conn1 次并执行一切?实际上,如果我这样做,它会向我发送一个错误,告诉我连接实际上是打开的

4

4 回答 4

3

我会把它全部放在try..catch中,打开你的连接,做所有需要的东西然后关闭连接。try..catch 的 finally 部分确保即使抛出错误也关闭连接:

    conn.Open()

try

    Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario)  VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn)
    guardador_datos2.ExecuteNonQuery()

    Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn)
    guardador_datos3.ExecuteNonQuery()

    Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn)
    guardador_datos4.ExecuteNonQuery()

catch ex as exception
    throw(ex)
finally
    conn.Close()
end try
于 2013-07-15T14:40:41.597 回答
2

正如错误试图告诉您的那样,如果连接已经打开,您将无法打开它。

您无需Open()多次调用。

于 2013-07-15T14:38:55.497 回答
2

您不需要多次打开连接,只需打开一次,关闭一次。我们经常做这样的事情:

conn.Open()
Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario)  VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn)
guardador_datos2.ExecuteNonQuery()

Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn)
guardador_datos3.ExecuteNonQuery()

Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn)
guardador_datos4.ExecuteNonQuery()
conn.Close()

您可能还希望将其包装在 Try/Catch/Finally 块中并使用事务,这样如果您的插入失败之一,它们都会回滚。

于 2013-07-15T14:41:34.617 回答
2

是的,您可以打开连接一次并在关闭连接之前执行多个命令。如果所有命令都将在相对接近的时间段内发生,我只建议这样做,听起来你正在这样做。

你不想做的是在你的应用程序启动时打开一个连接,并让它一直保持打开状态。

但是,如果您使用的是 MVC,则可能需要考虑使用 EntityFramework(或其他 ORM,如果您愿意)。然后您根本不必管理连接。

于 2013-07-15T14:42:00.620 回答