How will we use Connection Manager in Script component, using OLEDB Provider ? I had tried using Connection Manager with OLEDB Provider and SQL, but failed. what is the correct way to use ?
The syntax is different between a Script Task and a Script Component. Check out this article for more than a couple side-by-side comparisons:
http://msdn.microsoft.com/en-us/library/ms136031.aspx
This is well documented on MSDN, covering both VB and C# type of scripts: http://msdn.microsoft.com/en-us/library/ms136018.aspx
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
DataTable dtExcelData = new DataTable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();
Related
I have a database similar to the one below:
Table1(AutoNumber, Text, Number, Memo) // this is field types
Table1(ID, Title, Price, Image)
I'm trying to update an existing element of the database in C# using:
const string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=bd.mdb";
OleDbConnection m_dataBase = new OleDbConnection(connectionString);
OleDbConnection m_dataBase.Open();
SQL = "UPDATE Table1 SET Title='test', Price=35, Image='Test' WHERE ID=1";
OleDbCommand SQLQueryCommand = new OleDbCommand(SQL, m_dataBase);
int response = SQLQueryCommand.ExecuteNonQuery();
As a result I am getting this error. "Microsoft JET Database Engine Error syntax in UPDATE instruction".
What am I doing wrong?
PS: I can successfully do SELECT or INSERT, but not UPDATE.
Well, if your SQL command is the only problem, there are some visible issues.
Simply try to parametrize your Update clause using such as below which will prevent lots of little mistakes and also an SQL injection.
SQL = "UPDATE Table1 SET Title=?, Price=?, Image=? WHERE ID=?";
SQLQueryCommand.Parameter.Add("#MyTitle", OleDbType.VarChar).Value = "Test";
SQLQueryCommand.Parameter.Add("#MyPrice", OleDbType.Integer).Value = 35;
SQLQueryCommand.Parameter.Add("#MyImage", OleDbType.VarChar).Value = "TestAgain";
SQLQueryCommand.Parameter.Add("#MyID", OleDbType.VarChar).Value = 1;
To learn more about parametrization try having a look at the example in the bottom of this MSDN article.
OleDbCommand.Parameters Property
Also, it's a good practice to surround your connection inside a using statement.
using (var m_dataBase = new OleDbConnection(connectionString) { ... }
I'm using MySql database in ASP.NET MVC 4 project with MySqlClient (MySQL Connector .NET ).
In the References are dlls: MySql.Data, MySql.Data.Entry, MySql.Web
Selects from MySql database executes successfully, but inserts and updates are doesn't executes. No errors, no exceptions.
code №1:
var connectionString = "Server=my_server;Uid=my_login;Pwd=my_password;Old Guids=true;persist security info=True;database=clientest;allow zero datetime=True;convert zero datetime=True";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
String commandText = "update testdb.visit set doctor_spec='dentist' where visit_id = 2;";
MySqlCommand cmd = new MySqlCommand(commandText, conn);
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
No errors, no exception, but the table hasn't updates
code №2
using (var db = new MySqlDBEntities())
{
var vx = (from v in db.visit where v.visit_id == 1 select v).FirstOrDefault();
vx.doctor_spec = "dentist";
db.SaveChanges();
}
No errors, no exception, but the table hasn't updates.
What's wrong? Maybe another way for using MySql in ASP.NET MVC projects?
P.S. Sorry for my poor English :(
check connection in web config and find Correctly Data File
After Do Save Change Successfully any Edited Or New Entity Changes is Update
check this code too
* from v in db.visit /* db.visits */ where *
I work with google script and the JDBC connector to my MySQL database. I want to run a query using a variable, for example:
var rs = stmt.executeQuery("select*from Comuni where nomeComune=v");
How can I get JDBC to interpret the v at the end as a variable?
I would use just regular string concatenation - this is just JavaScript.
Why not to try the following:
var rs = stmt.executeQuery( "select * from Comuni where nomeComune={0}".format( value ) );
I have the following JScript code:
var conn = new ActiveXObject ("ADODB.Connection");
conn.Open("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=blah_blah_blah;User=foo;Password=bar;");
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE :search ORDER BY id";
var search = "test";
try{
cmd.CommandText = strSQL;
var param = cmd.CreateParameter(':search', 200, 1, 100, search);
cmd.Parameters.Append(param);
var rs = cmd.Execute();
}
catch (ex) {
Application.Alert("Error retrieving id information from database.");
}
I've verified (by printing them) that the Connection object is set to be the Command's ActiveConnection, the parameter object has the correct value and the Command object has the correct SQL query as its CommandText. I also inserted an alert statement after each line in the try block to see where the error was occuring - it's fine after cmd.Parameters.Append but the exception gets thrown upon running the Execute statement.
I've tried displaying the actual exception but it's just a generic 'Object error' message.
The query executes fine and returns the correct result set when I just execute the SQL query (without the parameter) straight through the Connection object, but seems to fail when I use a parameterised query with the Command object.
As far as I can see all settings and properties of the Command and Connection objects are correct but for whatever reason it's throwing an exception.
Any help with this would be much appreciated.
With ODBC and ADO, generally speaking, a question mark ? is used as the placeholder for parameters. Parameters are bound in the order they are appended to the Parameters collection to the placeholders in the command. In your example, replace strSQL with:
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE ? ORDER BY id";
You can still name the parameter that you create, but the only purpose it would serve is to be able to reference it by name later (e.g., with cmd.Parameters.Item(":search")).
I'm having trouble with the implementation of SqlDependency in my project.
I'm using SqlDependency in a WCF Service. WCF Service then holds in memory cache all results from all tables in order to have a huge speed gain. Everything seems to be working fine, except when I'm doing a table row update. If I add or delete a row in my table, DataContext is refreshed and cache is invalidated without problems. But when it comes to a table row update, nothing happens, the cache is not invalidated and when I look in debug mode at the content of DataContext, no changes seems to be there.
Here's the code I'm using (note that I'm using the System.Runtime.Caching object) :
public static List<T> LinqCache<T>(this Table<T> query) where T : class
{
ObjectCache cache = MemoryCache.Default;
string tableName =
query.Context.Mapping.GetTable(typeof(T)).TableName;
List<T> result = cache[tableName] as List<T>;
if (result == null)
{
using (SqlConnection conn =
new SqlConnection(query.Context.Connection.ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
query.Context.GetCommand(query).CommandText, conn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlDependency dependency = new SqlDependency(cmd);
SqlChangeMonitor sqlMonitor =
new SqlChangeMonitor(dependency);
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(sqlMonitor);
cmd.ExecuteNonQuery();
result = query.ToList();
cache.Set(tableName, result, policy);
}
}
return result;
}
I created an extension method so all I have to do is to query any table like that :
List<MyTable> list = context.MyTable.LinqCache();
My DataContext is opened at the Global.asax Application_OnStart and stored in cache, so I can use it whenever I want in my WCF Service. As well at this moment I'm opening the SqlDependency object with
SqlDependency.Start(
ConfigurationManager.ConnectionStrings[myConnectionString].ConnectionString);
So, is that a limitation of SqlDependency, or I'm doing something wrong/missing something in the process?
I think the problem is that although you do all the work in setting up the command object you then do:
cmd.ExecuteNonQuery();
result = query.ToList();
Which is going to use your SQL Command and throw away the results then LINQ to SQL will generate it's own internally via query.ToList(). Thankfully you can ask LINQ to SQL to execute your own command and translate the results for you so try replacing those two lines with:
results = db.Translate<T>(cmd.ExecuteReader());