前不久做了一个项目,在页面想数据库增加数据时遇到一个问题。之前为方便把主键id的操作,于是将id从int类型换成了varchar(32),这样在增加的时候就会出现错误“未将对象设置到实例”。就此写了个方法,在此与大家共享……
在增加的方法里面,先得到数据库的最大id:
/// <summary>
/// 判断增加还是修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnInsert_Click(object sender, EventArgs e)
{
int maxid= Business.KeyAdd.GetMaxID("id", "tableName");
……
……
}
GetMaxID()方法:
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Business 7 { 8 public static class KeyAdd 9 { 10 /// <summary> 11 /// 获取varchar32主键的最大ID值 12 /// </summary> 13 /// <param name="FieldName">主键列名</param> 14 /// <param name="TableName">数据表名</param> 15 /// <returns></returns> 16 public static int GetMaxID(string FieldName, string TableName) 17 { 18 string strsql = "select max(cast(" + FieldName + " as int)) from " + TableName; 19 object obj = DbHelperSQL.GetSingle(strsql); 20 if (obj == null) 21 { 22 return 0; 23 } 24 else 25 { 26 return int.Parse(obj.ToString()); 27 } 28 } 29 } 30 }
GetMaxID()方法里面调用DbHeperSql()方法:
View Code
1 public abstract class DbHelperSQL 2 { 3 //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. 4 private static readonly string connectionString = System.Configuration.ConfigurationManager.AppSettings["Con"]; 5 /// <summary> 6 /// 执行一条计算查询结果语句,返回查询结果(object)。 7 /// </summary> 8 /// <param name="SQLString">计算查询结果语句</param> 9 /// <returns>查询结果(object)</returns> 10 public static object GetSingle(string SQLString) 11 { 12 using (SqlConnection connection = new SqlConnection(connectionString)) 13 { 14 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 15 { 16 try 17 { 18 connection.Open(); 19 object obj = cmd.ExecuteScalar(); 20 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 21 { 22 return null; 23 } 24 else 25 { 26 return obj; 27 } 28 } 29 catch (System.Data.SqlClient.SqlException e) 30 { 31 connection.Close(); 32 throw e; 33 } 34 } 35 } 36 } 37 }
Web.config 配置:
<configuration> <appSettings> <add key="Con" value="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Pwd=xxx;Pooling=true;"/> </appSettings> …… </configuration>
因为初学,写得不是很好,还请见谅,如有不好的地方还请指出。