• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# MySqlConnection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中MySqlConnection的典型用法代码示例。如果您正苦于以下问题:C# MySqlConnection类的具体用法?C# MySqlConnection怎么用?C# MySqlConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MySqlConnection类属于命名空间,在下文中一共展示了MySqlConnection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MySqlConnection myConn = new MySqlConnection();
                myConn.Host = "192.168.69.8";
                myConn.Port = 3306;
                myConn.UserId = "cody";
                myConn.Password = "greenstreetelite";
                myConn.Open();

                MySqlCommand myCommand = new MySqlCommand(" SELECT * FROM registration.regUser ;", myConn);
                MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
                myDataAdapter.SelectCommand = myCommand;
                DataTable dbDataSet = new DataTable();
                myDataAdapter.Fill(dbDataSet);
                BindingSource bSource = new BindingSource();

                bSource.DataSource = dbDataSet;
                dataGridView1.DataSource = bSource;
                myDataAdapter.Update(dbDataSet);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
开发者ID:heidar-ali,项目名称:mysql-connector,代码行数:28,代码来源:Form1.cs


示例2: SearchForBook

    private static void SearchForBook(string input)
    {
        MySqlConnection dbConnection = new MySqlConnection(connection);

        dbConnection.Open();
        using (dbConnection)
        {

            string sqlStr = "USE `bookStores` ; SELECT AuthorName, titleBook, publishDate, ISBN  FROM books " +
                "JOIN authors " +
                "ON authors.Books_idBooks = books.idBooks " +
                "WHERE titleBook LIKE @input";
            MySqlParameter cmdParam = new MySqlParameter("@input", "%" + input + "%");
            MySqlCommand cmd = new MySqlCommand(sqlStr, dbConnection);
            cmd.Parameters.Add(cmdParam);
            MySqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string author = (string)reader["AuthorName"];
                string title = (string)reader["titleBook"];
                DateTime date = (DateTime)reader["publishDate"];
                long isbn = (long)reader["ISBN"];
                Console.WriteLine("{0}: {1} {2} {3}", author, title, date, isbn);
            }
        }
    }
开发者ID:Gerya,项目名称:TelerikAcademy,代码行数:26,代码来源:MySQLConn.cs


示例3: Button1_Click

    protected void Button1_Click(object sender, EventArgs e)
    {
        String aux = "INSERT INTO sala_apartada values(null," + TextBox2.Text + ", " + TextBox3.Text + ", '" + TextBox6.Text + "', '" + TextBox7.Text + "');";
        try
        {
            MySqlConnection Cn;
            MySqlCommand Cm;
            String cadena;
            Cn = new MySqlConnection();
            cadena = "Server=localhost; user=root; database=Laboratorio";
            Cn.ConnectionString = cadena;
            Cn.Open();
            /////Insertar/////
            Cm = new MySqlCommand(aux, Cn);
            Cm.ExecuteNonQuery();
            Cn.Close();
            Label1.Text = "Datos Guardados";
            //Response.Write(@"<script language='javascript'>alert('realizada')</script>");
        }

        catch (MySqlException es)
        {
           // Response.Write(@"<script language='javascript'>alert('Error')</script>");
            Label1.Text = "No se Pudo regsitrar Entrada";
        }
    }
开发者ID:Letractively,项目名称:al-fj-ser,代码行数:26,代码来源:apartar.aspx.cs


示例4: Add

    public void Add()
    {
        //con este metodo recogeremos los datos de los campos y realizaremos una insercion
        // a la base de datos mediante un mysqlcomand y lo ejecutaremos con mysqlNonquery.
        if(!ComprobarCampos()){
            conexion = pc.BuildConnection();
            using (con = new MySqlConnection(conexion)){
                MySqlCommand comando = new MySqlCommand();
                comando.Connection = con;

                comando.CommandType = CommandType.Text;
                comando.CommandText = "INSERT INTO personas (NOMBRE,APELLIDO,EDAD,SEXO,TELEFONO) " +
                    "values (@Nombre,@Apellido,@Edad,@Sexo,@Telefono)";
                comando.Parameters.AddWithValue("@Nombre", entry1.Text);
                comando.Parameters.AddWithValue("@Apellido", entry2.Text);
                comando.Parameters.AddWithValue("@Edad", entry4.Text);
                comando.Parameters.AddWithValue("@Sexo", combobox1.ActiveText);
                comando.Parameters.AddWithValue("@Telefono", entry3.Text);

                try{
                    con.Open();
                    comando.ExecuteNonQuery();
                }catch{
                    con.Dispose();
                    comando.Dispose();
                }
            }
        }
    }
开发者ID:ruben206,项目名称:rad,代码行数:29,代码来源:MainWindow.cs


示例5: bt_Gravar

    protected void bt_Gravar(object sender, EventArgs e)
    {
        string strConn_Access = ConfigurationManager.ConnectionStrings["ConnectionString_Listar"].ConnectionString;

        MySqlConnection MyConn = new MySqlConnection(strConn_Access);

        string sqlString = "INSERT INTO perguntas " +
                "(Pergunta, Dificuldade, CapituloId, TipoPg) " +
                "VALUES (@Pergunta, @Dificuldade, @CapituloId, @TipoPg);";

        MySqlCommand Cmd = new MySqlCommand(sqlString, MyConn);

        Cmd.Parameters.AddWithValue("@Pergunta", Editor.Content);
        Cmd.Parameters.AddWithValue("@Dificuldade", txt_Dificuldade.Text);
        Cmd.Parameters.AddWithValue("@CapituloId", Drop_Capitulo.Text);
        Cmd.Parameters.AddWithValue("@TipoPg", Drop_Tipo.Text);

        try
        {
            MyConn.Open();

            Cmd.ExecuteNonQuery();

            MyConn.Close();

            lbl_erro.Text = "Dados introduzidos com sucesso!";
            lbl_erro.Visible = true;

        }
        catch (Exception ex)
        {
            lbl_erro.Text = "Houve um erro na introdução dos dados";
            lbl_erro.Visible = true;
        }
    }
开发者ID:portugol,项目名称:si,代码行数:35,代码来源:Inserir.aspx.cs


示例6: Button1_Click

    protected void Button1_Click(object sender, EventArgs e)
    {
        String idSalaT = TextBox4.Text;
        String fecha = "'" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "'";

          // idSalaT=lis

        String consulta = "Insert into mantenimiento values (null, " + fecha + ", " + idSalaT+ ", " + TextBox2.Text.ToString() + ", '" + TextBox3.Text.ToString() + "');";

        // statusMaquina.Text = consulta;

        try
        {
            MySqlConnection Conexion = new MySqlConnection();
            String cadena;
            cadena = "Server=localhost; user=root; database=Laboratorio";
            Conexion.ConnectionString = cadena;
            Conexion.Open();
            MySqlCommand command = new MySqlCommand(consulta, Conexion);
            command.ExecuteNonQuery();
            Conexion.Close();
            Label1.Text = "Datps Guardados";
            //s = true;
        }

        catch (MySqlException ex)
        {
            //Response.Write("<script language='javascript'>alert('Verifica tus Datos')</script>");
            Label1.Text = " Verifica tus Datos";

        }
    }
开发者ID:Letractively,项目名称:al-fj-ser,代码行数:32,代码来源:Reporte.aspx.cs


示例7: MainWindow

    //ListStore listStore;
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();

        IDbConnection dbConnection= new MySqlConnection("Server=localhost;Database=dbprueba;" +
                "User Id=root;Password=sistemas");
        dbConnection.Open();

        ComboBoxHelper combo= new ComboBoxHelper(dbConnection,Combobox,"nombre","id",1,"categoria");
        //listStore=combo.ListStore;

        //		TreeIter iter;
        //		liststore.GetIterFirst(out iter);
        //		do{
        //			if((int)liststore.GetValue(iter,0)==elementoInicial){
        //				break;
        //			}
        //		}
        //		while(liststore.IterNext(ref iter));

        Combobox.Changed +=delegate{
            Console.WriteLine("El id es {0}",combo.ID);
        };
    }
开发者ID:nerea123,项目名称:ad,代码行数:26,代码来源:MainWindow.cs


示例8: Button1_Click

    protected void Button1_Click(object sender, EventArgs e)
    {
        string sqlQuery;
        string connstr = "server=localhost;user id=admin;password=123456;database=mydb";
        if (this.bid.Value.CompareTo("1") == 0)
        {
            sqlQuery = "update admin set login=0 where rid='" + this.rid.Value + "'";
        }
        else
        {
            sqlQuery = "update reader set login=0 where rid='" + this.rid.Value + "'";
        }

        using (MySqlConnection conn = new MySqlConnection(connstr))
        {
           // string sqlQuery = "update admin,reader set login=1 where rid='" + this.rid.Value + "'";
            MySqlCommand comm = new MySqlCommand(sqlQuery, conn);
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                throw new Exception("数据库连接失败!", ex);
            }
            comm.ExecuteNonQuery();

        }
        Response.Redirect("Default2.aspx");
    }
开发者ID:shanghai-Jerry,项目名称:SmartLib,代码行数:30,代码来源:Default.aspx.cs


示例9: CreatePatient

    public bool CreatePatient(string fname, string lname, string dob, string sex)
    {
        if ((String.IsNullOrWhiteSpace(fname)) | (String.IsNullOrWhiteSpace(lname)) | (!Patient.IsValidDOB(dob)) | (!Patient.IsValidSex(sex)))
        {
            return false;
        }
        try
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
            MySqlConnection connection = new MySqlConnection(connString);
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = "INSERT INTO patient (first_name, last_name, birth_date, sex) VALUES (@fname, @lname, @dob, @sex)";
            command.Parameters.Add("fname", MySqlDbType.String).Value = fname;
            command.Parameters.Add("lname", MySqlDbType.String).Value = lname;
            command.Parameters.Add("dob", MySqlDbType.Date).Value = String.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(dob));
            command.Parameters.Add("sex", MySqlDbType.Enum).Value = sex;

            connection.Open();
            command.ExecuteReader();
            connection.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }
开发者ID:azach,项目名称:Sembe,代码行数:27,代码来源:PatientService.cs


示例10: LecturaDeDatos

	protected void LecturaDeDatos()
	{

		mySqlConnection = new MySqlConnection("DataSource=localhost;" +
		                                      "Database=dbprueba;" +
		                                      "User ID=root;" +
		                                      "Password=sistemas");
		mySqlConnection.Open ();

	    mySqlCommand = mySqlConnection.CreateCommand ();

		mySqlCommand.CommandText = "select * from categoria";

		MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader ();


		//Console.WriteLine ("id.GetType()={0}", IDbCommand.GetType());//Muestra el tipo de dato utilizado

		while (mySqlDataReader.Read()) {

			object id = mySqlDataReader["id"].ToString();
			object nombre = mySqlDataReader["nombre"];
			listStore.AppendValues (id, nombre);

		}
		mySqlDataReader.Close ();

	}
开发者ID:rlloret,项目名称:AD,代码行数:28,代码来源:MainWindow.cs


示例11: Page_Load

 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
     /*string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;*/
     string constr = "server=182.50.133.91;database=Techgeekinc_db;" + "uid=techgeek;pwd=techgeek786;";
         using (MySqlConnection con = new MySqlConnection(constr))
         {
             using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM customers"))
             {
                 using (MySqlDataAdapter sda = new MySqlDataAdapter())
                 {
                     cmd.Connection = con;
                     sda.SelectCommand = cmd;
                     using (DataTable dt = new DataTable())
                     {
                         sda.Fill(dt);
                         GridView1.DataSource = dt;
                         GridView1.DataBind();
                     }
                 }
             }
         }
     }
 }
开发者ID:Techgeekinc,项目名称:techgeek,代码行数:25,代码来源:CS.aspx.cs


示例12: DB

 public DB(string str = "")
 {
     if (str == "")
         str = _conStr;
     _connection = new MySqlConnection(str);
     _connection.Open();
 }
开发者ID:nokitty,项目名称:chaxin,代码行数:7,代码来源:DB.cs


示例13: Main

    static void Main(string[] args)
    {
        string connToMySql = @"Server=localhost;Uid=root;Pwd=root;Allow User Variables=True;";

        MySqlConnection connect = new MySqlConnection(connToMySql);

        connect.Open();

        using (connect)
        {
            CreateDB(connect);

            InsertBook(connect, "Steven McTowlie", "A Million Little Fibers", "41124114512125512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie2", "A Million Little Fibers2", "411124114512125512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie3", "A Million Little Fibers3", "4112411451212512X", "1995, 04, 12");
            InsertBook(connect, "Steven McTowlie4", "A Million Little Fibers4", "41124114512532125512X", "1995, 04, 12");

            ListAllBooks(connect);

            Console.Write("Enter a search word:");
            string searchString = Console.ReadLine().Replace("%", "[%]")
                                                .Replace("_", "[_]");
            Console.WriteLine();
            FindBookByName(connect, searchString);
        }
    }
开发者ID:C3co0o0o,项目名称:Databases,代码行数:26,代码来源:09.MySQL-Conneciton-And-CRUD.cs


示例14: InsertBook

 private static void InsertBook(MySqlConnection dbCon)
 {
     Console.WriteLine("Enter Book title");
     string title = Console.ReadLine();
     title = EscapeSQLString(title);
     Console.WriteLine("Enter Book author");
     string author = Console.ReadLine();
     author = EscapeSQLString(author);
     Console.WriteLine("Enter Book publish date in format dd.MM.yyyy");
     DateTime publishDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US"));
     Console.WriteLine("Enter Book ISBN");
     string isbn = Console.ReadLine();
     isbn = EscapeSQLString(isbn);
     using (dbCon)
     {
         MySqlCommand cmdInsert = new MySqlCommand(
             "INSERT INTO Books(Title, Author, PublishDate, ISBN) " +
             "VALUES (@title, @author, @publishDate, @isbn)", dbCon);
         cmdInsert.Parameters.AddWithValue("@title", title);
         cmdInsert.Parameters.AddWithValue("@author", author);
         cmdInsert.Parameters.AddWithValue("@publishDate", publishDate);
         cmdInsert.Parameters.AddWithValue("@isbn", isbn);
         cmdInsert.ExecuteNonQuery();
     }
 }
开发者ID:vasilkrvasilev,项目名称:Databases,代码行数:25,代码来源:MySQL.cs


示例15: StateChange

		public void StateChange() 
		{
			MySqlConnection c = new MySqlConnection(GetConnectionString(true));
			c.StateChange += new StateChangeEventHandler(StateChangeHandler);
			c.Open();
			c.Close();
		}
开发者ID:elevate,项目名称:mysqlconnector-.net,代码行数:7,代码来源:EventTests.cs


示例16: ListBooks

    private static void ListBooks(MySqlConnection dbCon)
    {
        using (dbCon)
        {
            MySqlCommand cmdSelect = new MySqlCommand(
                "SELECT * FROM Books", dbCon);

            Console.WriteLine("Books:");
            Console.WriteLine("ID\tTitle\t\tAuthor\t\tPublish Date\tISBN");
            MySqlDataReader reader = cmdSelect.ExecuteReader();
            using (reader)
            {
                while (reader.Read())
                {
                    int id = (int)reader["BookId"];
                    string title = (string)reader["Title"];
                    string author = (string)reader["Author"];
                    DateTime publishDate = (DateTime)reader["PublishDate"];
                    string isbn = (string)reader["ISBN"];
                    Console.WriteLine("{0}\t{1}\t{2}\t{3:dd.MM.yyyy}\t{4}",
                        id, title.Trim(), author.Trim(), publishDate, isbn.Trim());
                }
            }
        }
    }
开发者ID:vasilkrvasilev,项目名称:Databases,代码行数:25,代码来源:MySQL.cs


示例17: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] == null || (string)Session["usertype"] == "vender")
        {
            Response.Redirect("Login_Page.aspx");
        }
        else
        {
            Button1.Text = Session["username"].ToString();
            String poNum = Request.QueryString["p"];
            pn = poNum;
            String itemid = Request.QueryString["i"];
            ii = itemid;

            Label1.Text = poNum;
            Label2.Text = itemid;

            String uid = Session["uid"].ToString();

            string connStr = "Database=ISI;Data Source=localhost;User Id=root;Password=123999";
            mySqlConn = new MySqlConnection(connStr);
            mySqlConn.Open();

           
            
        }

        
    }
开发者ID:Douglasli,项目名称:ISIproject,代码行数:29,代码来源:Rating_review.aspx.cs


示例18: Button1_Click

    protected void Button1_Click(object sender, EventArgs e)
    {
        bool dondur = Filtrele.filtrelencek(TextBox1.Text + " " + TextBox2.Text);
        if (dondur)
        {
            MySqlConnection baglanti = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["a"].ConnectionString);
            string str = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "sha1");
            baglanti.Open();
            MySqlCommand Sorgu = new MySqlCommand("Select * from user where email='" + TextBox1.Text + "' and password='" + str + "'", baglanti);

            MySqlDataReader oku = Sorgu.ExecuteReader();
            if (oku.Read())
            {
               
                Session["asd"] =oku["id"];
                Response.Redirect("Default.aspx");
            }
            else
            {
                Response.Write("<script language=javascript>alert('Error! incorrect password  or user  ');</script>");
            }
            baglanti.Close();
        }
        else { Response.Write("<script language=javascript>alert('Çakall!! SQL sorguları kullanma');</script>"); }
    }
开发者ID:webertuar,项目名称:asd,代码行数:25,代码来源:login.aspx.cs


示例19: ProblemCharsInSQLUTF8

    public void ProblemCharsInSQLUTF8()
    {
      if (Version < new Version(4, 1)) return;

      execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), mt MEDIUMTEXT, " +
            "PRIMARY KEY(id)) CHAR SET utf8");

      using (MySqlConnection c = new MySqlConnection(GetConnectionString(true) + ";charset=utf8"))
      {
        c.Open();

        MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?text, ?mt)", c);
        cmd.Parameters.AddWithValue("?id", 1);
        cmd.Parameters.AddWithValue("?text", "This is my;test ? string–’‘’“”…");
        cmd.Parameters.AddWithValue("?mt", "My MT string: ?");
        cmd.ExecuteNonQuery();

        cmd.CommandText = "SELECT * FROM Test";
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
          Assert.IsTrue(reader.Read());
          Assert.AreEqual(1, reader.GetInt32(0));
          Assert.AreEqual("This is my;test ? string–’‘’“”…", reader.GetString(1));
          Assert.AreEqual("My MT string: ?", reader.GetString(2));
        }
      }
    }
开发者ID:jimmy00784,项目名称:mysql-connector-net,代码行数:27,代码来源:Syntax.cs


示例20: sprAdmin

    protected bool sprAdmin(int id)
    {
        string connStr = ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString;
        MySqlConnection conn = new MySqlConnection(connStr);

        try
        {
            conn.Open();

            string sql = "SELECT typ FROM users WHERE [email protected];";
            MySqlCommand zapytanie = new MySqlCommand(sql, conn);

            zapytanie.Parameters.Add(new MySqlParameter("@Id", Session["id"].ToString()));

            object wynik = zapytanie.ExecuteScalar();

            if (wynik != null && wynik.ToString() == "A")
            {
                conn.Close();
                return true;
            }

            conn.Close();
        }
        catch (MySqlException ex)
        {
            //Blad.InnerHtml = ex.ToString();
        }

        return false;
    }
开发者ID:EddyEND,项目名称:Przychodnia_empty,代码行数:31,代码来源:MasterAdmin.master.cs



注:本文中的MySqlConnection类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# MySqlDataAdapter类代码示例发布时间:2022-05-24
下一篇:
C# MySqlCommand类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap