I have a little problem with my MysqlConnection objets. I have those two connection strings in my app.config :
<connectionStrings>
<add name="bdpvcLocalhost" connectionString="Persist Security Info=False;server=localhost;Uid=root;Password=***;database=bdpvc" providerName="Mysql.Data.MySqlClient"/>
<add name="bdpvcProduction" connectionString="server=pvcserver.pvcservprod.local;user id=pvc_app;Pwd=***;database=bdpvc" providerName="Mysql.Data.MySqlClient"/>
</connectionStrings>
The first connection is for a local test database, the second one is for the real production database. Since i am still early in the developpement, I use my local database. I then use the following code (I cut some of the Parameters definition cause there is really a lot)
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
connection.Open();
using (MySqlTransaction transaction = connection.BeginTransaction())
{
const string sequenceQuery = "INSERT INTO sequence " +
"(No_Sequence, No_Client, No_Produit, No_Version_Produit, " +
" No_Soumission, No_Commande, No_Reference, Date_Livraison, " +
"Date_Commande, Date_Soumission, Quantite, Status, Contact, " +
"Notes, No_Production_Ancien, Erreur_Production, No_Fichier_Log, " +
"No_Utilisateur, Date_Enregistrement, Extension_Fichier_Fax, Uuid) " +
"VALUES(?No_Sequence, ?No_Client, ?No_Produit, ?No_Version_Produit, " +
"?No_Soumission, ?No_Commande, ?No_Reference, ?Date_Livraison, ?Date_Commande, " +
"?Date_Soumission, ?Quantite, ?Status, ?Contact, ?Notes, ?No_Production_Ancien, " +
"?Erreur_Production, ?No_Fichier_Log, ?No_Utilisateur, ?Date_Enregistrement, " +
"?Extension_Fichier_Fax, ?Uuid)";
const string selectSequenceNoQuery =
"SELECT MAX(No_Sequence) AS Valeur_No_Increment FROM sequence";
const string updateSequenceNoQuery =
"UPDATE tables SET Valeur_No_Increment = ?Valeur_No_Increment WHERE Nom_Tables = 'sequence'";
int currentIncrement = 0;
MySqlCommand selectNoSequenceCommand = new MySqlCommand(selectSequenceNoQuery, connection,
transaction);
MySqlCommand updateNoSequenceCommand = new MySqlCommand(updateSequenceNoQuery, connection,
transaction);
MySqlCommand insertSequenceCommand = new MySqlCommand(sequenceQuery, connection, transaction);
//------------------------------
//This query execute perfectly!
currentIncrement = Int32.Parse(selectNoSequenceCommand.ExecuteScalar().ToString());
insertSequenceCommand.Parameters.Add("?No_Sequence", MySqlDbType.String);
//Lots and lot of parameters definition
foreach (Sequence sequence in _sequences)
{
currentIncrement++;
sequence.No_Sequence = currentIncrement.ToString();
insertSequenceCommand.Parameters["?No_Sequence"].Value = sequence.No_Sequence;
//Lots and lots of value assignement
//---------------------------------
//But this one doesn't use the right user!
insertSequenceCommand.ExecuteNonQuery();
Console.WriteLine("Inserted new sequence with Uuid " + sequence.Uuid + " and increment " +
sequence.No_Sequence);
}
updateNoSequenceCommand.Parameters.AddWithValue("?Valeur_No_Increment", currentIncrement);
updateNoSequenceCommand.ExecuteNonQuery();
transaction.Commit();
}
}
The first query execute just fine. However, the second query isn't able to execute, because "the user pvc_app doesn't exists". But I am connecting to my local database as root! And never in my code do I switch connection string! I tried deleting the second connection string in app.config, but it kept trying to connect as pvc_app. I rebuild the application multiple time, rebooted my computer and even uninstalled/reinstalled the ADO.NET connector, but it kept trying to connect as pvc_app! Am I doing something wrong here?
Now, where is located this mysterious "connection string cache" so I can kill it with my bare hand? Cause it's really making my life a misery right now.
A workaround of this problem was to create an another user with a default password. The connection was then working fine. It seem to be a bug with ADO.NET connector.
Related
i have the following code which has been getting me data from flat files. but now all of a sudden i am getting this error
System.Data.OleDb.OleDbException: Invalid path or file name
but the code hasnt changed it worked for months,im not sure what went wrong.
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonText;
System.Collections.Generic.List<object> objList = new List<object>();
string strConn = #"Provider=vfpoledb;Data Source=\\10.0.0.0\wwwroot\apps\assembly\FlatDatabaseDbfs\vt_Flat.dbf;Collating Sequence=machine;";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn))
{
System.Data.OleDb.OleDbCommand cmddbf = new System.Data.OleDb.OleDbCommand();
cmddbf.Connection = conn;
conn.Open();
cmddbf.CommandText = "select * from vt_Flat";
var dr = cmddbf.ExecuteReader();
while (dr.Read())
{
objList.Add(new
{
Code = (dr["dp_code"].ToString().Trim()),
});
};
}
var filteredList = objList.Where(obj => ((dynamic)obj).Status == (Request.QueryString["Status"] ?? "") && ((dynamic)obj).DepCode == (Request.QueryString["Code"] ?? ""));
jsonText = json.Serialize(filteredList);
Response.Write(jsonText);
}
is there something wrong with iis permissions?
Aside from the connection having to point to the PATH as already noted by Oleg, in the C# instances of OleDbConnection I have done in the past, the connection string uses
Provider=VFPOLEDB.1
Don't know if it is case/sensitive issue and the ".1" which is also part of the provider string.
Once you have a valid connection to the PATH, then your query can query from any table within the path location. So if you had 2+ files, and needed to join them, you would do so with a standard query / join. In your case, your command text is only "select *" since you changed your original connection that included the table. Change the command text to
"select * from vt_Flat"
OTHER CONSIDERATIONS
Is this being run from some web service project? If so, THAT could be the basis. You as a developer testing are running with your permissions / access. If running as a web server, the WEB-based user account may not have permissions to the folder to process / work with the data.
Check the folder of your production data to ALLOW the web user if so running. If that doesn't work, set permissions on the folder to EVERYBODY (only for testing/confirmation purposes only). See if that is the problem.
Also, from the Provider connection, did you try with it as all upper case VFPOLEDB.1?
Use path instead of file name, e.g.:
Data Source=\\10.0.0.0\wwwroot\apps\assembly\FlatDatabaseDbfs\;
I want to create a SSIS package which writes a file with data generated by executing a SQL Statement. This generic package will be invoked by other packages passing in correct SQL as a variable.
Thus in the generic package :
I want to execute a dynamic SELECT query and fetch dynamic number of columns from a single database instance, the connection string does not per call and store the result into a flat file.
What would be an ideal way to accomplish this in SSIS.
What I tried :
The simplest solution that I could find was a writing a script task which would open a SQL connection , execute the SQL using SQLCommand, populate a datatable using the data fetched and write the contents directly to the file system using System.io.File and Release the connection.
I tried using OLE Database source with the SQLsupplied by a variable (with Validation set to false) and directing the rows into a Flat file connection. However due to the dynamic number and names of the columns I ran into errors.
Is there a more standard way of achieving this without using a script task?
How about this ... concatenate all field values into one field, and map AllFields to a field in a text file destination.
SELECT [f1]+',' + [f2] AS AllFields FROM [dbo].[A]
All of the "other"packages will know how to create the correct SQL. Their only contract with the "generic" package would be to eventually have only one field nameed "AllFields".
To answer your question directly, I do not think there is a "standard" way to do this. I believe the solution from Anoop would work well and while I have not tested the idea I wish I would have investigated it before writing my own solution. You should not need a script task in that solution...
In any case, I did write my own way to generate csv files from SQL tables that may run up against edge cases and need polishing but works rather well right now. I am looping through multiple tables before this task so the CurrentTable variable can be replaced with any variable you want.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
string TableName = Dts.Variables["User::CurrentTable"].Value.ToString();
string FileDelimiter = ",";
string TextQualifier = "\"";
string FileExtension = ".csv";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["connection manager name"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Read data from table or view to data table
string query = "Select * From [" + TableName + "]";
SqlCommand cmd = new SqlCommand(query, myADONETConnection);
//myADONETConnection.Open();
DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
//myADONETConnection.Close();
string FileFullPath = Dts.Variables["$Project::ExcelToCsvFolder"].Value.ToString() + "\\Output\\" + TableName + FileExtension;
StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);
// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;
for (int ic = 0; ic < ColumnCount; ic++)
{
sw.Write(TextQualifier + d_table.Columns[ic] + TextQualifier);
if (ic < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
for (int ir = 0; ir < ColumnCount; ir++)
{
if (!Convert.IsDBNull(dr[ir]))
{
sw.Write(TextQualifier + dr[ir].ToString() + TextQualifier);
}
if (ir < ColumnCount - 1)
{
sw.Write(FileDelimiter);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
//using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString() + "\\" +
// "ErrorLog_" + datetime + ".log"))
//{
// sw.WriteLine(exception.ToString());
//}
Dts.TaskResult = (int)ScriptResults.Failure;
throw;
}
Dts.TaskResult = (int)ScriptResults.Success;
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 *
Here is my Scenario
I have MS Access DB (MDB file), and work group security file. I have credentials which have all the permit (Administrator user). This DB and MDW file is created on some other computer and i am using it on my computer now.
What I am able to do till now is, I can log in the DB with different user name and password which are existing in the DB. Verified this by using Correct user name and wrong password It give error, but correct credentials it logins.
Now I need to create a interface In Java to basic functionality.
1. Change password of currently logged user.
Change password of current user
Following is my code to change the password
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:"+"mdbTEST";
// mdbTEST is created in System DNS which uses SECURED.MDW file and
// ExtendedAnsiSQL is set to 1
conn = DriverManager.getConnection(database, "administrator", "hello");
String q = "ALTER USER "+uname+" PASSWORD "+newPass+" '"+oldPass+"'";
stmt = conn.createStatement();
stmt.execute(q);
It returns successful.
But when I try to log in the with the username and new password it says wrong passowrd and even the old password stops working.
Moreover, I tried to read all the username and passwords in the WorkGroup file using some third party software, it shows the new password is updated correctly in the MDW file.
I am using JDK 1.7 on Windows XP 32 bit.
What can be the problem? Am I doing something wrong here?
Thanks in Advance.
If you want to put quotes around the password values to accommodate passwords that contain spaces, you should enclose them in double quotes ("). If you enclose them in single quotes (') then the single quote characters become part of the password. For example, after executing my test code...
import java.sql.*;
public class ulsTest {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=C:\\Users\\Public\\uls\\ulsTest.mdb;" +
"SystemDB=C:\\Users\\Public\\uls\\Security.mdw;" +
"Uid=Gord;" +
"Pwd=obfuscated;" +
"ExtendedAnsiSQL=1;");
String UID = "Tim";
String oldPWD = "oldpassword";
String newPWD = "I like Java";
Statement s = conn.createStatement();
s.execute("ALTER USER " + UID + " PASSWORD \"" + newPWD + "\" \"" + oldPWD + "\"");
// ALTER USER Tim PASSWORD "I like Java" "oldpassword"
System.out.println("User updated.");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
...Tim is able to log in using the new password
I like Java
However, if I change my code to...
s.execute("ALTER USER " + UID + " PASSWORD '" + newPWD + "' '" + oldPWD + "'");
// ALTER USER Tim PASSWORD 'I like Java' 'oldpassword'
...then the single quotes become part of the new password and Tim must type the password...
'I like Java'
...(including the single quotes) to log in.
Side note: I was hoping that a parameterized query might avoid messing with string quoting, but unfortunately the code...
PreparedStatement s = conn.prepareStatement("ALTER USER ? PASSWORD ? ?");
s.setString(1, UID);
s.setString(2, newPWD);
s.setString(3, oldPWD);
s.execute();
...fails with the error:
[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.
I am developing a web application with database access using Spring, JDBCTemplate and c3p0.
I often have a server freeze, and I am pretty sure it comes from the number of busy database connections. If I watch the application behavior, using jconsole, I can see that the maxPoolSize of the ComboPooledDataSource is reached, and the server doesn't load a page anymore.
Here is the useful code:
DataSource definition:
<Resource auth="Container" description="GDLWeb DB Connection"
driverClass="org.postgresql.Driver"
maxPoolSize="16"
minPoolSize="1"
acquireIncrement="1"
maxIdleTime="60"
maxStatements="0"
idleConnectionTestPeriod="1800"
acquireRetryAttempts="30"
breakAfterAcquireFailure="true"
name="jdbc/gdlweb"
user="gdlweb"
password=""
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:postgresql://localhost:5432/postgres"
/>
Typical access method (in DAO class):
protected T getPersistentObject(
final String tableName,
final List<WhereClause> whereParams,
final RowMapper<T> rowMapper) {
try {
log.debug(this, "get " + tableName + " " + whereParams);
return (T) getTemplate().queryForObject(
generateSelectStar(tableName, whereParams),
extractValueMap(whereParams),
rowMapper);
} catch (final EmptyResultDataAccessException e) {
log.warning(this, "No " + tableName + " found with " + whereParams + " in the DB!");
return null;
}
}
I tried to increase the maxPoolSize to 100, which is the maxConnections defined in my postgresql server. This way, I could see that there were 43 busy connections currently openned, just before the postgresql server crashes.
I am probably using JDBCTemplate the wrong way, but I don't know where.
Thanks.
The problem may be with the Mysql Connector/J version you are using.
I had the same issue, updating to the new Mysql Connector v5.1.15 solved it for me. v5.1.13 has a bug which results in the problems you are seeing
Change-log for the version which fixes the bug: http://dev.mysql.com/doc/refman/5.1/en/cj-news-5-1-14.html
Thanks