我正在尝试执行SQL命令,但我无法找出为什么这不起作用。 这就是我在名为“clsSQL”的类中定义“execute”函数的方法:
''#...
Private m_sConnectionString As String = String.Empty
''#...
Friend WithEvents m_objConnection As SqlConnection
Friend WithEvents m_objCommand As SqlCommand
''#...
Public Function OpenConnection() As Boolean
Try
m_objConnection = New SqlConnection(m_sConnectionString)
m_objConnection.Open()
Select Case m_objConnection.State
Case Data.ConnectionState.Open : Return True
Case Else : Return False
End Select
Catch ex As Exception
RaiseEvent OnError("OpenConnection", ex)
End Try
End Function
Public Function Execute(ByVal sQuery As String) As Boolean
Try
#If DEBUG_MODE Then
Debug.WriteLine(sQuery)
#End If
m_objCommand = New SqlCommand(sQuery, m_objConnection)
m_objCommand.ExecuteNonQuery()
m_objCommand = Nothing
Return True
Catch ex As Exception
RaiseEvent OnError("Execute", ex)
End Try
End Function
''#..
''#...
这就是我的称呼方式:
Using oSQL As New clsSQL(My.Settings.projectConnectionString)
If oSQL.OpenConnection Then
strSQL = "INSERT INTO ... blablabla..."
oSQL.Execute(strSQL)
End If
End Using
代码不会引发错误,只是不保存数据库中的数据。错误不在SQL命令中,我手动测试了它;)
例如,我可以完美地执行下一个函数而没有任何问题:
Public Function ToDataGrid(ByVal oDataGrid As DataGridView, _
ByVal sQuery As String, _
Optional ByVal sTable As String = "") As Boolean
Try
#If DEBUG_MODE Then
Debug.WriteLine(sQuery)
#End If
Dim objDataSet As New DataSet
objDataSet = ToDataSet(sQuery, sTable)
oDataGrid.DataSource = objDataSet.Tables(0)
objDataSet.Dispose()
objDataSet = Nothing
Return True
Catch ex As Exception
RaiseEvent OnError("ToDataGrid", ex)
End Try
End Function
这就是我所说的:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using oSQL As New clsSQL(My.Settings.projectConnectionString)
If oSQL.OpenConnection Then
oSQL.ToDataGrid(Me.DataGridView, "select * from table")
End If
End Using
End Sub
可能,我只需要另一双眼睛,因为我看不出我做错了什么:|
由于
答案 0 :(得分:1)
我不确定这是否是错误的原因,只是好奇你在哪里设置了这个变量?
m_objConnection
为了调试,您可以评论try / catch语句。 IMO
答案 1 :(得分:1)
您的代码看起来没问题,您能否向我们展示INSERT语句。您是否尝试使用SQL事件探查器来查看您的INSERT是否完全访问数据库?
这是我前面写过的一个SQL类,你可以使用:
using System;
using System.Data.SqlClient;
namespace SAPCommonData
{
public class SQLClass : IDisposable
{
private String connString;
private SqlCommand SQLCmd;
private SqlConnection SQLConn;
public void Dispose()
{
if (SQLCmd != null)
{
SQLCmd.Dispose();
SQLCmd=null;
}
if (SQLConn != null)
{
SQLConn.Dispose();
SQLConn = null;
}
}
public String SQLConnString
{
get{ return connString; }
set{ connString = value; }
}
private String GetSQLConnString()
{
String strConn;
try
{
strConn = System.Configuration.ConfigurationSettings.AppSettings.Get("SQL_CONN");
}
catch (Exception ex)
{
throw (new System.Exception(ex.Message.ToString()));
}
return strConn;
}
public void SQLExecuteNonQuery()
{
if (SQLCmd == null)
{
throw (new System.Exception("Must use SetSQLCommand to initialize SQLCommand object!"));
}
if (SQLConn == null)
{
OpenSQLDB();
}
try
{
SQLCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (new System.Exception(ex.Message.ToString()));
}
finally
{
SQLCmd.Dispose();
SQLCmd=null;
}
}
public SQLClass()
{
try {
connString = GetSQLConnString();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
try
{
SQLConn = new SqlConnection(connString);
SQLConn.Open();
}
catch (Exception e)
{
throw (new System.Exception(e.Message.ToString()));
}
}
public void OpenSQLDB()
{
if (IsOpen())
{
//connection state open already
}
else
{
if (connString.Length == 0)
{
try
{
connString = GetSQLConnString();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
}
try
{
SQLConn = new SqlConnection(connString);
SQLConn.Open();
}
catch (Exception e)
{
throw (new System.Exception(e.Message.ToString()));
}
}
}
public bool IsOpen()
{
return (SQLConn.State == System.Data.ConnectionState.Open);
}
public void CloseSQLDB()
{
if (IsOpen())
{
SQLConn.Dispose();
SQLConn.Close();
SQLConn=null;
}
}
public String SQLDBUsed()
{
return SQLConn.Database;
}
public void SetSQLCommand(String proc)
{
if (proc.Length == 0)
{
throw new System.Exception("Procedure must be specified when calling SetSQLCommand!");
}
if (SQLConn == null)
{
OpenSQLDB();
}
SQLCmd = new SqlCommand(proc, SQLConn);
SQLCmd.CommandType = System.Data.CommandType.StoredProcedure;
}
public void AddSQLCmdParameter(String pName, System.Data.SqlDbType pType, object pVal)
{
if (SQLCmd == null)
{
throw (new System.Exception("Must use SetSQLCommand to initialize SQLCommand object!"));
}
if (SQLConn == null)
{
OpenSQLDB();
}
try
{
SQLCmd.Parameters.Add(pName, pType).Value = pVal;
}
catch (Exception ex)
{
throw (new System.Exception(ex.Message.ToString()));
}
}
public void ClearSQLCmdParameters()
{
if (SQLCmd != null)
{
SQLCmd.Parameters.Clear();
}
}
public void DisposeSQLCmd()
{
if (SQLCmd != null)
{
SQLCmd.Dispose();
}
}
public System.Data.SqlClient.SqlDataReader SQLExecuteReader()
{
System.Data.SqlClient.SqlDataReader dr;
if (SQLCmd == null)
{
throw (new System.Exception("Must use SetSQLCommand to initialize SQLCommand object!"));
}
if (SQLConn == null)
{
OpenSQLDB();
}
try
{
dr = SQLCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
throw (new System.Exception(ex.Message.ToString()));
}
finally
{
SQLCmd.Dispose();
SQLCmd=null;
}
return dr;
}
}
}
然后你可以重复使用这个对象:
public void ProcessCustomerData(DataTable dt)
{
//we have a valid connection to the database
if (dt.Rows.Count > 0)
{
try
{
s=new SQLClass();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
foreach(DataRow dr in dt.Rows)
{
tw.WriteLine("Processing customer: " + dr["NAME1"].ToString());
Console.WriteLine("Processing customer: " + dr["NAME1"].ToString());
s.SetSQLCommand("insCustomer");
s.AddSQLCmdParameter("@ClientID", System.Data.SqlDbType.Int, dr["MANDT"]);
s.AddSQLCmdParameter("@CustomerID", System.Data.SqlDbType.BigInt, dr["KUNNR"]);
s.AddSQLCmdParameter("@CustomerName1", System.Data.SqlDbType.VarChar, ((string)dr["NAME1"]==String.Empty ? DBNull.Value : dr["NAME1"]));
s.AddSQLCmdParameter("@CustomerName2", System.Data.SqlDbType.VarChar, ((string)dr["NAME2"]==String.Empty ? DBNull.Value : dr["NAME2"]));
s.AddSQLCmdParameter("@Country", System.Data.SqlDbType.VarChar, ((string)dr["LAND1"]==String.Empty ? DBNull.Value : dr["LAND1"]));
s.AddSQLCmdParameter("@Region", System.Data.SqlDbType.VarChar, ((string)dr["REGIO"]==String.Empty ? DBNull.Value : dr["REGIO"]));
s.AddSQLCmdParameter("@City", System.Data.SqlDbType.VarChar, ((string)dr["ORT01"]==String.Empty ? DBNull.Value : dr["ORT01"]));
s.AddSQLCmdParameter("@ZipCode", System.Data.SqlDbType.VarChar, ((string)dr["PSTLZ"]==String.Empty ? DBNull.Value : dr["PSTLZ"]));
s.AddSQLCmdParameter("@Address", System.Data.SqlDbType.VarChar, ((string)dr["STRAS"]==String.Empty ? DBNull.Value : dr["STRAS"]));
s.AddSQLCmdParameter("@Telephone", System.Data.SqlDbType.VarChar, ((string)dr["TELF1"]==String.Empty ? DBNull.Value : dr["TELF1"]));
s.AddSQLCmdParameter("@Fax", System.Data.SqlDbType.VarChar, ((string)dr["TELFX"]==String.Empty ? DBNull.Value : dr["TELFX"]));
s.AddSQLCmdParameter("@DateAdded", System.Data.SqlDbType.DateTime, System.DateTime.Today);
s.AddSQLCmdParameter("@DateModified", System.Data.SqlDbType.DateTime, System.DateTime.Today);
s.AddSQLCmdParameter("@AddedBy", System.Data.SqlDbType.VarChar, DBNull.Value);
s.AddSQLCmdParameter("@ModifiedBy", System.Data.SqlDbType.VarChar, DBNull.Value);
s.SQLExecuteNonQuery();
Console.WriteLine("Processed customer: " + dr["NAME1"].ToString());
tw.WriteLine("Processed customer: " + dr["NAME1"].ToString());
}
s.CloseSQLDB();
s.Dispose();
}
}
答案 2 :(得分:1)
Catch : End Try
中的OpenConnection
屏蔽异常并隐藏您从未连接到数据库的事实,因此从不执行SQL吗?
此外,它看起来好像你没有关闭连接。
答案 3 :(得分:1)
我的猜测是SQL语句中存在阻止插入发生的条件。
鉴于没有抛出任何异常,我敢打赌,实际上该语句正在被处理,但是WHERE子句阻止了任何行的插入。
我会调查一下。
答案 4 :(得分:1)
你班级的New()函数在哪里?你可以在你的类中的OpenConnection()函数中调试m_sConnectionString吗?您是否从该功能获得True返回值?如果你的oSQL.OpenConnection失败,你没有'Else'子句,所以你不知道你是否正在连接。
答案 5 :(得分:0)
Visual Studio创建了一个副本 数据库文件,将其添加到您的 项目,并修改连接 所以它现在指向数据库 在你的项目中。
http://msdn.microsoft.com/en-us/library/ms246989%28VS.80%29.aspx