在Visual Basic中执行大量SQL命令的更好方法?

时间:2013-07-15 14:36:32

标签: sql vb.net asp.net-mvc-4

我正在使用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(我在这里只举三个例子,但实际上有9个conn.Open和{{1} })。

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

由于错误试图告诉您,如果连接已经打开,则无法打开连接。

您无需多次致电Open()

答案 2 :(得分: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块中并使用事务,这样如果其中一个插入失败,则所有插入都会回滚。

答案 3 :(得分:2)

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

您不想做的事情是在您的应用启动时打开一个连接,并在整个时间内保持打开状态。

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