服务器端向mysql数据库写数据

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Drawing;
using System.Data;
using MySQLDriverCS;
using System.Web.Script.Serialization;

namespace GLSXJSON2.Controllers
{
    public class AdviseInsertController : Controller
    {

        public string Index(string text)  //这里的text是从service文件中获取的参数
        {
            MySQLConnection conn = null;
            conn = new MySQLConnection(new MySQLConnectionString("localhost", "glsx", "root", "ecust2016", 3306).AsString);
            conn.Open();     //这几句为建立一个MySQL的连接conn




            //sql语句写成string形式
            string str0 = string.Format("select MAX(Id) from fag order by Id desc");

            int id;
            MySQLCommand cmd0 = new MySQLCommand(str0, conn);        //建立MySQL执行命令cmd0 参数为str0和conn
            if(cmd0.ExecuteScalar()!=null&&!Convert.IsDBNull(cmd0.ExecuteScalar())){//执行查询操作,ExecuteScalar()返回查询结果第一行
                id=int.Parse(cmd0.ExecuteScalar().ToString())+1;      //这是不为空情况把id+1
            }
            else
                id=0;      //若为空id置0



            //sql语句写成string形式
            string str = string.Format("insert into fag(Id,content) values({0},'{1}')", id, text);

            try
            {
                MySQLCommand cmd = new MySQLCommand(str, conn);     //建立MySQL执行命令cmd 参数为str和conn
                cmd.ExecuteNonQuery();  //返回执行的条数
                return "1";      //执行成功返回1
            }
            catch
            {
                return "-1";         //失败返回-1
            }
             
        }

    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-08-20
  • 2022-01-05
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-02-06
  • 2022-02-06
  • 2022-03-07
  • 2022-12-23
相关资源
相似解决方案