当前位置: 首页>>代码示例>>C#>>正文


C# MySqlConnection类代码示例

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


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


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