table not created - android-sqlite

The project executes but table is not created. My codes
{
public HelperData(Context context) {
super(context, database_name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String creat = "Create table " + Table_name + "(" + KEY_ID
+ " Integer primary key autoincrement," + KEY_FNAME + "TEXT,"
+ KEY_LNAME + "TEXT" + ");";
Log.d("Tag", "==table created" + creat);
db.execSQL(creat);
}
}
What might be the issue?

I can't see what the content of those Strings (like KEY_FNAME or KEY_LNAME) is but it appears you don't have a space between the strings that define the column names and their data types.
E.g.:
If String KEY_LNAME = "something",
KEY_LNAME + "TEXT" can result in something like "somethingTEXT" instead of "something TEXT".
If that is the case, you can either add a space to the end of the column name string (e.g. String KEY_LNAME = "something ") or add the space before the column data type (... KEY_LNAME + " TEXT" ...).
Also, look at Logcat, there may be some Exceptions being thrown.
I may be wrong, as I don't know what those strings of yours contain, but that's my guess.

Related

MyBatis multi-row INSERT using SQL Builder

I am using MyBatis (mybatis-spring-boot-starter 2.0), I want to insert list of values into table using java sqlBuilder. I know how to write sqlBuilder in java for storing single record. But how to write the sqlBuilder for List of records?
Mapper interface (Single record):
#InsertProvider(method = "insert", type = TestSqlBuilder.class)
#Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
public void save(final TestVO testVO );
TestSqlBuilder.java (Single record):
The below method used for inserting single TestVO values.
public String insert() {
return new SQL() {
{
INSERT_INTO("TEST")
.VALUES("COL1", "#{col1}")
.VALUES("COL2", "#{col2}")
.VALUES("COL3", "#{col3}")
.VALUES("COL3", "#{col4}")
.toString();
}
}.toString();
}
Now for List of records, how to write sqlBuilder.
Else how can we convert the below to sqlBuilder java code
#Insert("<script> "
+ "insert into sys_user "
+ "(t_id, t_name, t_age) "
+ "values "
+ "<foreach collection='list' item='item' "
+ " index='index' separator=','> "
+ "(#{item.id}, #{item.name}, #{item.age}) "
+ "</foreach> "
+ "</script> ")
int insertUserListWithForeach(List<User> list);

Query always returns false in Sqlite Android

I want to check the username and password with sqlite table,In my case query always returns false...
This is my Query...
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
if (c!=null)
{
return true;
}
else{
return false;
}
}
Checking whether or not the Cursor is null is basically useless as a valid Cursor will be returned by rawQuery. That is no data to extract will result in an empty Cursor with no rows, whilst if data has been extracted the Cursor will have 1 or more rows.
You should check whether or not the Cursor is empty by using the Cursor getCount() method which will return 0 if there are no rows or the number of rows. Alternately you could use some of the Cursor's move methods which will return true/false depending upon whether the move can be performed. e.g if (c.moveToFirst) { ... //row(s) exist} else { ... //no rows exists }.
You should also close the Cursor before returning. So perhaps use :-
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
int count = c.getCount(); // get the number of rows
c.close(); // Close the Cursor
return count > 0; // return result (no data found = false, else true)
Many would recommend not using rawQuery but rather the convenience Cursor query method. This could be :-
public boolean validateUser(String u_name, String p_word) {
String[] columns = new String[]{
FNAME,
PASSWORD
};
String whereclause = FNAME + "=? AND " + PASSWORD + "=?";
String[] whereargs = new String[]{
u_name,
p_word
};
Cursor c = this.getWritableDatabase().query(
TABLE_NAME,
columns,
whereclause,
whereargs,
null,null,null
);
int count = c.getCount();
c.close();
return count > 0;
}
Note the above code is in-principle code and hasn't been tested so it may contain typing errors.
The above code assumes that the method is within the Database Helper class (i.e. a subclass of SQLiteOpenHelper).
The assumption has been made that FNAME and PASSWORD are the correct String variables to be used for the column names as opposed to fname and password
Assumptions have been made due to the limited code made available.

load data into table hive

I'm trying to Configure Hive to Work with JDBC and I used this exemple on eclipse :
public class HiveJdbcClient {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
/**
* #param args
* #throws SQLException
**/
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/default", "", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.executeQuery("drop table " + tableName);
ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
// describe table
sql = "describe " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1) + "\t" + res.getString(2));
}
// load data into table
// NOTE: filepath has to be local to the hive server
// NOTE: /tmp/test_hive_server.txt is a ctrl-A separated file with two fields per line
String filepath = "/tmp/test_hive_server.txt";
sql = "load data local inpath '" + filepath + "' into table " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
// select * query
sql = "select * from " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()){
System.out.println(String.valueOf(res.getInt(1)) + "\t" + res.getString(2));
}
// regular hive query
sql = "select count(1) from " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()){
System.out.println(res.getString(1));
}
}
}
I was able to create the table on hive but when I try to load data into the table an error appears . so my question is what should I put into "test_hive_server.txt" to make it work! Because I tried everything and each time I get the same error.
Thanks!
the error:
Exception in thread "main" java.sql.SQLException: org.apache.thrift.TApplicationException: Internal error processing execute
at org.apache.hadoop.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:196)
at com.palmyra.nosql.HiveJdbcClient.main(HiveJdbcClient.java:52)
I found the answer by myself actually the :
ROW FORMAT DELIMITED FIELDS TERMINATED BY ' ';
determinate the format of the rows in the "file.txt" that we are going to load in the table and Hive’s default record and field delimiters list is :
\n
^A
^B
^C
press ^V^A could insert a ^A in Vim.
or you can just do:
create table tableName (key int, value string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ' ';
and the 'file.txt' should be like this:
value1 value2
value3 value4
in this example value1 and value3 represent the key
and value4 and value5 represent the value

Entity Framework - Table-Valued Functions - Parameter Already Exists

I am using table-valued functions with Entity Framework 5. I just received this error:
A parameter named 'EffectiveDate' already exists in the parameter collection. Parameter names must be unique in the parameter collection. Parameter name: parameter
It is being caused by me joining the calls to table-valued functions taking the same parameter.
Is this a bug/limitation with EF? Is there a workaround? Right now I am auto-generating the code (.edmx file).
It would be really nice if Microsoft would make parameter names unique, at least on a per-context basis.
I've created an issue for this here.
In the meantime, I was able to get this to work by tweaking a few functions in the .Context.tt file, so that it adds a GUID to each parameter name at runtime:
private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) {
if (typeMapper.IsComposable(edmFunction))
{
#>
[EdmFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")]
<#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#>
{ var guid = Guid.NewGuid().ToString("N"); <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, " + guid", WriteFunctionParameter);
#>
<#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#>
} <#+
}
else
{
#>
<#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#>
{ <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, "", WriteFunctionParameter);
#>
<#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#>
} <#+
if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption))
{
WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true);
}
} }
...
public void WriteFunctionParameters(EdmFunction edmFunction, string nameSuffix, Action<string, string, string, string> writeParameter)
{
var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
{
var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", " + parameter.FunctionParameterName + ")";
var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", typeof(" + parameter.RawClrTypeName + "))";
writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
}
}
...
public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
{
var parameters = _typeMapper.GetParameters(edmFunction);
return string.Format(
CultureInfo.InvariantCulture,
"return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
_typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
edmFunction.NamespaceName,
edmFunction.Name,
string.Join(", ", parameters.Select(p => "#" + p.EsqlParameterName + "\" + guid + \"").ToArray()),
_code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
}
Not a bug. Maybe a limitation or an omission. Apparently this use case has never been taken into account. EF could use auto-created parameter names, but, yeah, it just doesn't.
You'll have to resort to calling one of the functions with .AsEnumerable(). For some reason, this must be the first function in the join (as I have experienced). If you call the second function with .AsEnumerable() it is still translated to SQL and the name collision still occurs.

Template to show method name and parameter values in Eclipse

Is there any way to have a template (Java -> Editor -> Templates) in Eclipse that generate something like this
debug("methodName arg1=" + arg1 + " arg2=" + arg2 + " arg3=" + arg3);
When used in a method. For instance:
public void setImage(long rowId, long contactId, String thinggy) {
// invoking the template here, produces this:
debug("setImage rowId=" + rowId + " contactId=" + contactId + " thinggy=" + thinggy);
}
I couldn't find a way to do that with the standard template UI, maybe there exists a plugin to do this kinds of things?
This is a start:
debug("${enclosing_method_arguments}: ", ${enclosing_method_arguments});
which produces the following:
debug("arg1, arg2, arg3: ", arg1, arg2, arg3);
I haven't found a way to separate out each argument. I found this page that ran into the same problem.
For other Eclipse template stuff, look at this question.
I guess it's probably a bit too late to answer this question but maybe my answer will help someone :
System.out.println(String.format("%tH:% %s", java.util.Calendar.getInstance(), "${enclosing_package}.${enclosing_type}.${enclosing_method}(${enclosing_method_arguments})"));
String[] lArgsNames = new String("${enclosing_method_arguments}").split(", ");
Object[] lArgsValues = new Object[] {${enclosing_method_arguments}};
for (int i = 0; i < lArgsValues.length; i++) {
System.out.println("\t" + (lArgsValues[i] != null ? ("(" + lArgsValues[i].getClass().getSimpleName() + ") \"" + lArgsNames[i] + "\" = \"" + lArgsValues[i] + "\"") : "\"" + lArgsNames[i] + "\" is null"));
}
For this method :
public void foo(boolean arg){
// ...
}
the output would be:
18:43:43:076 > any.package.AnyClass.foo(arg)
(Boolean) "arg" = "true"
This code seems to be able to handle any object, primitive type and null value. And yes it's a little bit complicated for the purpose!
I've made small plugin that adds nicely formatted variable:
https://github.com/dernasherbrezon/eclipse-log-param
Eclipse doesnt provide any information about parameter type, so there is no Arrays.toString(...)
or template=
if (aLog.isDebugEnabled()) {
aLog.debug(String.format("${enclosing_method}:${enclosing_method_arguments}".replaceAll(", ", "=%s, ")+"=%s", ${enclosing_method_arguments}));
}
gives
public static void hesteFras(boolean connect, Object ged, String frans, int cykel) {
if (aLog.isDebugEnabled()) {
aLog.debug(String.format("hesteFras: connect, ged, frans, cykel".replaceAll(", ", "=%s, ") + "=%s",
connect, ged, frans, cykel));
}
which for
hesteFras(false, null, "sur", 89);
gives a log statement:
hesteFras: connect=false, ged=null, frans=sur, cykel=89
The eclipse-log-param plugin is useful to avoid having to type the logging line manually. However, it would be even nicer to have the line added automatically for all new methods.
Is this even possible? It looks like in Windows->Preferences->Code Style->Code Templates->Code there are ways to configure automatically added code like auto-generated methods ("Method body" template, which has an "Auto-generated method stub" comment). But there's no way to configure new methods which are not generated.
Furthermore, the variable formatted_method_parameters is not available when editing the template for "Method body".