1、存储
由于double类型在SQLsever中并没有对应数据,试过对应float、real类型,发现小数位都存在四舍五入的现象,目前我使用的是decimal类型,用此类型时个人觉得小数位数应该比自己的数据中小数位数设置的多一点,不然还是会出现四舍五入。
以下是我的代码,由于业务需求,我的数据库只存储一条数据,一直更新
using (SqlConnection con = new SqlConnection(connectionString)) { try { //dbHelper = new DBHelper(BCSSqlConnection); con.Open(); StringBuilder sbSql = new StringBuilder(); //sbSql.Append("insert into GpsData("); //sbSql.Append("lon,lat,AddTime)"); //sbSql.Append(" values ("); //sbSql.Append(" @lon,@lat,@AddTime)"); sbSql.Append("update GpsData set lon = @lon ,lat = @lat,AddTime=@AddTime where id = 1"); string strInsertSql = sbSql.ToString(); SqlCommand cmd = new SqlCommand(strInsertSql, con); cmd.Parameters.Add("@lon", lon); cmd.Parameters.Add("@lat", lat); cmd.Parameters.Add("@AddTime", DateTime.Now); cmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine("添加失败了" + ex.Message); //表示数据库异常 } finally { con.Close(); } }
2.读取
2.1 从数据库中取出数据
using (SqlConnection con = new SqlConnection(connectionString)) //using (BCSSqlConnection = new MySqlConnection(mysqlcon)) { try { con.Open(); StringBuilder sbSql = new StringBuilder(); sbSql.Append("select lon,lat from GpsData"); SqlCommand com = new SqlCommand(sbSql.ToString(), con); SqlDataAdapter da = new SqlDataAdapter(com); DataTable dt = new DataTable(); da.Fill(dt); //返回DataTable对象dt return dt; } catch (Exception e) { throw new Exception(e.Message); } finally { con.Close(); } }
2.2 数据类型转换
DataTable dt = mm.SelectGpsData(); double lon = Convert.ToDouble(dt.Rows[0]["lon"].ToString()); double lat = Convert.ToDouble(dt.Rows[0]["lat"].ToString()); Console.WriteLine(lon + " " + lat);