我创建了会员维护代码,我将在其中检索会员ID,姓名和所有基本内容 我的代码如下:
private void Mem_Maintenance_Load(object sender, EventArgs e)
{
try
{
txt_mem_id.Text = Generate_no.gen_no("MEM").ToString();
}
catch(Exception Ex)
{
MessageBox.Show("Error\n\n"+Ex.ToString());
}
}
我创建了一个名为Library的ClassLibrary,其代码如下
namespace LIBRARY
{
public class Generate_no
{
public static int gen_no(string P_PRM_TYPE)
{ OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\arekh\MS Access\soc_data.accdb;Persist Security Info=False;";
connection.Open();
int v_last_no = 0;
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = @"select PARM_VALUE from soc_parm_mast where PARM_TYPE = '" + P_PRM_TYPE + "';";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1;
reader.Close();
command.CommandText = @"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = " + P_PRM_TYPE + ";";
command.ExecuteNonQuery();
connection.Close();
return v_last_no;
}
}
}
但在执行过程中会出现错误
System.FormatException:输入字符串格式不正确 LIBRARY.Generate_no.gen_no(String P_PRM_TYPE)
答案 0 :(得分:0)
command.CommandText = @"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = '" + P_PRM_TYPE + "';";
您在更新语句中缺少单引号
答案 1 :(得分:0)
导致指定错误的行v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1;
,如果输入不可转换,Int32.Parse
将抛出FormatException
。所以我强烈建议你使用Int32.TryParse()
。然后代码如下:
public static int gen_no(string P_PRM_TYPE)
{
using (OleDbConnection connection = new OleDbConnection(@"Connection string here"))
{
connection.Open();
int v_last_no = 0;
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
string query = @"select PARM_VALUE from soc_parm_mast where PARM_TYPE = @P_PRM_TYPE";
command.CommandText = query;
command.Parameters.AddWithValue("@P_PRM_TYPE", P_PRM_TYPE);
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
if (!Int32.TryParse(reader["PARM_VALUE"].ToString(), out v_last_no))
{
// Conversion failed, Show message if needed
// v_last_no will be 0
}
reader.Close();
}
using (OleDbCommand command = new OleDbCommand())
{
command.CommandText = @"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE =@P_PRM_TYPE";
command.Parameters.AddWithValue("@P_PRM_TYPE", P_PRM_TYPE);
command.ExecuteNonQuery();
}
}
return v_last_no;
}
还有一个建议:在使用Concatenated字符串作为查询时要小心SQL注入。请改用参数化查询。