webapi连接mysql_WebApi连接数据库

费学
2023-12-01

首先在web.config中加上语句连接语句:

然后再控制器中测试

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Text;

using System.Web.Http;

using System.Web.Http.Cors;

using WebApplication.Models;

using System.Configuration;

namespace WebApplication.Controllers

{

public class ValuesController : ApiController

{

[EnableCors(origins: "*", headers: "*", methods: "*")]

// GET api/values

public IEnumerable Get()

{

return new string[] { "value1", "value2" };

}

// GET api/values/5

public Object Get(int id)

{

//return "value";

try

{

string connectionString = ConfigurationManager.ConnectionStrings["conn"].ToString();//引用的 using System.Configuration;

SqlConnection conn = new SqlConnection(connectionString);

//打开数据

conn.Open();

string sql = "select * from information where id=@id";

SqlCommand cmd = conn.CreateCommand();

cmd.CommandText = sql;

cmd.Parameters.Add(new SqlParameter("@id", id));

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);

DataSet dataSet = new DataSet();

sqlDataAdapter.Fill(dataSet);

return dataSet;

}

catch (Exception ex)

{

return ex;

}

}

// POST api/values

[HttpPost]

public object Post([FromBody] UserModel userModel)

{

try

{

打开数据

//conn.Open();

//string sql = "INSERT INTO information([idcard],[bianma])VALUES(@idcard,@bianma)";

//SqlCommand cmd = conn.CreateCommand();

//cmd.CommandText = sql;

//cmd.Parameters.Add(new SqlParameter("@idcard", "20181026"));

//cmd.Parameters.Add(new SqlParameter("@bianma", "1026"));

//SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);

//DataSet dataSet = new DataSet();

//sqlDataAdapter.Fill(dataSet);

//return dataSet;

var strName = String.Format("一个对象,{0},{1}", userModel.bianma,userModel.idcard);

return strName;

}

catch (Exception ex)

{

return false;

}

}

// PUT api/values/5

public void Put(int id, [FromBody]string value)

{

}

// DELETE api/values/5

public void Delete(int id)

{

}

}

}

 类似资料: