MySQL数据库(五)_VS中实现插入MySQL数据<21/9/2017>
妻子作为丈夫的外键,所以必须先声明;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace OneToOne
{
class Program
{
static MySqlConnection myConnnect;
static void Main(string[] args)
{
string constructorString = "server=localhost;User Id=root;password=;Database=vr";
myConnnect = new MySqlConnection(constructorString);
myConnnect.Open();
Wife w = new Wife();
w.Id = 1;
w.Name = "马蓉";
Husband h = new Husband();
h.Id = 1;
h.Name = "王宝强";
h.wife = w;
Save(StringInSql(w));
Save(StringInSql(h));
//ORM -- 对象关系映射
myConnnect.Close();
}
public static string StringInSql(Wife w)
{
return "insert into wife values(" + w.Id + ",'" + w.Name + "');";
}
public static string StringInSql(Husband h)
{
return "insert into husband values(" + h.Id + ",'" + h.Name + "'," + h.wife.Id + ");";
}
public static void Save(string insertTarget)
{
MySqlCommand comd = new MySqlCommand(insertTarget, myConnnect);
try
{
if (comd.ExecuteNonQuery() > 0)
{
Console.WriteLine("数据插入成功");
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
}
public class Wife
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Husband
{
public int Id { get; set; }
public string Name { get; set; }
public Wife wife { get; set; }
}
}
在cmd中打开MySQL先建立妻子的表,再建立丈夫的表,因为妻子是丈夫的外键,不然会报错,删除也要注意:
运行代码实现VS插入数据成功,然后删除数据;